【问题标题】:Forward Geocoding with Swift使用 Swift 进行正向地理编码
【发布时间】:2016-11-18 04:57:38
【问题描述】:

我希望能够让用户输入地址,并能够保存该地址,并将其转换为纬度和经度坐标。我找不到太多关于正向地理编码的文档,而且我在启动此代码时遇到了麻烦。我应该要求用户按(城市、州、邮政编码)输入地址吗?还是一个地址就足够了?有没有可以做我需要的功能?非常感谢任何帮助。

【问题讨论】:

    标签: swift mkmapview geocoding


    【解决方案1】:

    我在 github 上做了一个简单的 LocationManager 助手,你可以在其中得到你想要的东西。

    库中有一个函数getReverseGeoCodedLocation。只需将您的地址作为字符串输入并获取完整的地标和纬度、经度。

    在您的项目中添加LocationManager.swift 文件

    使用方法:-

    LocationManager.sharedInstance.getReverseGeoCodedLocation(address: yourAddress, completionHandler: { (location:CLLocation?, placemark:CLPlacemark?, error:NSError?) in
    
            if error != nil {
                print((error?.localizedDescription)!)
                return
            }
    
            if placemark == nil {
                print("Location can't be fetched")
                return
            }
    
            print(placemark?.addressDictionary?.description ?? "")
            print((placemark?.location?.coordinate.latitude)!)
            print((placemark?.location?.coordinate.longitude)!)
    
    })
    

    在内部它使用geocodeAddressStringCLGeocoder

    输出

    注意:- 适用于 Swift 3.0 及以上版本

    【讨论】:

    • 嗨@Rajan Maheshwari,你在github上发布的代码正是我想要的!但是,我将 LocationManager.swift 文件输入到我的项目中,并使用上面的代码,将地址变量输入到 yourAddress 中,但是,当我尝试转换它时,它不打印任何东西(甚至不打印错误)。您知道可能出了什么问题吗?
    • @Kevin 您在地址字符串中输入了什么以及您使用的是哪个 xcode 版本?
    • 是否也使用调试器是否进入完成块?我刚刚在 textView 中写了新德里,它打印了完整的经纬度和地址
    • 我刚刚使用字符串“New York City”作为地址变量对其进行了测试。我也在使用 Swift 3.0。如何在代码中使用调试器?
    • 我也做了同样的事情并发布了截图。检查我的答案中的编辑。您应该已连接到互联网
    【解决方案2】:

    如果您想避免付费 Google Maps API(用于商业目的)和使用 CLLocation,您还可以查看 NominatimSwift:https://github.com/caloon/NominatimSwift 如果您只想进行地理编码,它可能是最轻量级的解决方案。 (免责声明:我做到了)

    NominatimSwift 使用免费的 Nominatim API 对 OpenStreetMap 数据进行地理编码。您还可以搜索地标。它需要网络连接。

    地理编码地址和地标:

    Nominatim.getLocation(fromAddress: "The Royal Palace of Stockholm", completion: {(error, location) -> Void in
      print("Geolocation of the Royal Palace of Stockholm:")
      print("lat = " + (location?.latitude)! + "   lon = " + (location?.longitude)!)
    })
    

    反向地理编码:

    Nominatim.getLocation(fromLatitude: "55.6867243", longitude: "12.5700724", completion: {(error, location) -> Void in
      print("City for geolocation 55.6867243/12.5700724:")
      print(location?.city)
    })
    

    【讨论】:

      猜你喜欢
      • 2016-01-01
      • 2018-05-30
      • 1970-01-01
      • 1970-01-01
      • 2021-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多