2016-11-18 8 views
0

我期望能夠讓用戶輸入一個地址,並且能夠保存該地址並將其轉換爲緯度和縱向座標。我一直無法找到關於前向地理編碼的大量文檔,並且在啓動此代碼時遇到問題。我應該要求用戶輸入地址(城市,州,郵政編碼)嗎?或者只有一個地址就足夠了?有沒有可以做我需要的功能?任何幫助深表感謝。使用Swift轉發地理編碼

回答

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

輸出

enter image description here 的注意: - 那是爲了雨燕3.0及以上

+0

嗨@Rajan Maheshwari,你貼在GitHub上的代碼正是我一直在尋找!但是,我將LocationManager.swift文件輸入到了我的項目中,並使用上述代碼,將地址變量輸入到地址中,但是,當我嘗試轉換它時,它不打印任何內容(甚至不包括錯誤)。你有什麼想法可能會出錯? – Kevin

+0

@Kevin你在地址字符串中輸入了什麼,你使用的是哪種xcode版本? –

+0

也可以使用調試器,無論它是否進入完成塊內部?我剛剛在textView中寫了新德里,它印刷了完整的經緯度,地址 –

0

如果你想避免支付谷歌地圖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) 
})