2017-02-16 227 views
-1

如何使用Swift將String地址轉換爲CLLocation座標?我還沒有代碼,我尋找一個解決方案,但我還沒有找到任何人。將地址轉換爲座標swift

謝謝。

+4

你真的搜查,沒有發現什麼?你有沒有閱讀Apple的CoreLocation文檔? https://developer.apple.com/reference/corelocation/clgeocoder –

回答

26

這是很容易的。

let address = "1 Infinite Loop, Cupertino, CA 95014" 

    let geoCoder = CLGeocoder() 
    geoCoder.geocodeAddressString(address) { (placemarks, error) in 
     guard 
      let placemarks = placemarks, 
      let location = placemarks.first?.location 
     else { 
      // handle no location found 
      return 
     } 

     // Use your location 
    } 

您還需要添加和導入CoreLocation框架。

+0

我在哪裏使用「位置」變量? – Arcadian

5

您可以使用CLGeocoder,你可以轉換地址(字符串),以協調和你相反,試試這個:

import CoreLocation 

var geocoder = CLGeocoder() 
geocoder.geocodeAddressString("your address") { 
    placemarks, error in 
    let placemark = placemarks?.first 
    let lat = placemark?.location?.coordinate.latitude 
    let lon = placemark?.location?.coordinate.longitude 
    print("Lat: \(lat), Lon: \(lon)") 
} 
+0

我該如何返回一個CLLocation值? –

+0

placemark?.location是一個CLLocation類型。 – Greg

2

這工作

let geocoder = CLGeocoder() 
let address = "8787 Snouffer School Rd, Montgomery Village, MD 20879" 
     geocoder.geocodeAddressString(address, completionHandler: {(placemarks, error) -> Void in 
      if((error) != nil){ 
       print("Error", error ?? "") 
      } 
      if let placemark = placemarks?.first { 
       let coordinates:CLLocationCoordinate2D = placemark.location!.coordinate 
       print("Lat: \(coordinates.latitude) -- Long: \(coordinates.longitude)") 
      } 
     })