geocodeAddressString不适用于swift

时间:2017-07-14 03:47:25

标签: swift core-location clgeocoder

您好我正在尝试使用geocodeAddressString将地址转换为地图上的地标,但无论我传递给此方法的地址是什么,下面的块都不会被执行,任何人都可以给我一些亮点吗?非常感谢 顺便说一句,我可以在concole上看到“之前”和“之后”,但没有“你好”

  let geo = CLGeocoder()
    print("before")
    geo.geocodeAddressString(("4 Bradford St, Perth WA 6050"), completionHandler: {
        (placemarks, error) -> Void in

        print ("hello")
        if let placemark = placemarks?[0]
       {
          self.mapView.addAnnotation(MKPlacemark(placemark: placemark))
        }
    })

  print ("after")

3 个答案:

答案 0 :(得分:2)

使用此

import CoreLocation

let address = "1 Infinite Loop, CA, USA"
let geocoder = CLGeocoder()

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
      }
    })

答案 1 :(得分:1)

试试这段代码:

geocoder.geocodeAddressString(("4 Bradford St, Perth WA 6050"), completionHandler: {(placemarks, error) -> Void in

                    if let placemark = placemarks?.first {
                        let coordinates:CLLocationCoordinate2D = placemark.location!.coordinate
                        coordinates.latitude
                        coordinates.longitude


                        self.lat = coordinates.latitude
                        self.long = coordinates.longitude
                        print("lat \(self.lat)")
                        print("long \(self.long)")
                    }
                })

答案 2 :(得分:1)

使用此

    import CoreLocation

    let address = "4 Bradford St, Perth WA 6050"
    let geocoder = CLGeocoder()

    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
          }
        })


var address = "4 Bradford St, Perth WA 6050"
var geocoder = CLGeocoder()
geocoder.geocodeAddressString(address, {(placemarks: [AnyObject]!, error: NSError!) -> Void in
    if let placemark = placemarks?[0] as? CLPlacemark {
        self.mapView.addAnnotation(MKPlacemark(placemark: placemark))
    }
})