使用 Swift 进行正向地理编码

Forward Geocoding with Swift

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

我在 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)!)

})

在内部它使用 CLGeocoder

geocodeAddressString

输出

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

如果您想避免付费 Google 地图 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)
})