2017-02-16 174 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)") 
      } 
     })