Convert GPS coordinates to a city name / address in Swift

自作多情 提交于 2019-12-22 05:25:03

问题


I have a latitude/longitude location that I want to convert to the location name String in Swift. What is the best way to do this? i believe it's best to use the reverseGeocodeLocation function but not exactly sure how to. This is what I have so far:

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
    if (locationFixAchieved == false) {
        locationFixAchieved = true
        var locationArray = locations as NSArray
        var locationObj = locationArray.lastObject as CLLocation
        var coord = locationObj.coordinate
        var latitude = coord.latitude
        var longitude = coord.longitude

        getCurrentWeatherData("\(longitude)", latitude: "\(latitude)")
        reverseGeocodeLocation(location:coord, completionHandler: { (<#[AnyObject]!#>, <#NSError!#>) -> Void in
            <#code#>
        })

    }
}

func reverseGeocodeLocation(location: CLLocation!, completionHandler: CLGeocodeCompletionHandler!){

}

回答1:


You need to write the code like this:

geocoder.reverseGeocodeLocation(currentLocation, completionHandler: {
            placemarks, error in

                if error == nil && placemarks.count > 0 {
                    self.placeMark = placemarks.last as? CLPlacemark
                    self.adressLabel.text = "\(self.placeMark!.thoroughfare)\n\(self.placeMark!.postalCode) \(self.placeMark!.locality)\n\(self.placeMark!.country)"
                    self.manager.stopUpdatingLocation()
                }
            })



回答2:


I am using Swift 3 / XCode 8

I used Benjamin Herzog's answer but I ran into some build errors related to optional and casting.

In rewriting it, I decided to encapsulate it in a function and generalize it so it can easily be plugged in anywhere.

import CoreLocation

func getPlacemark(forLocation location: CLLocation, completionHandler: @escaping (CLPlacemark?, String?) -> ()) {
    let geocoder = CLGeocoder()

    geocoder.reverseGeocodeLocation(location, completionHandler: {
        placemarks, error in

        if let err = error {
            completionHandler(nil, err.localizedDescription)
        } else if let placemarkArray = placemarks {
            if let placemark = placemarkArray.first {
                completionHandler(placemark, nil)
            } else {
                completionHandler(nil, "Placemark was nil")
            }
        } else {
            completionHandler(nil, "Unknown error")
        }
    })

}

Using it:

getPlacemark(forLocation: originLocation) { 
    (originPlacemark, error) in
        if let err = error {
            print(err)
        } else if let placemark = originPlacemark {
            // Do something with the placemark
        }
    })
}



回答3:


please check this answer.

 func getAddressFromGeocodeCoordinate(coordinate: CLLocationCoordinate2D) {
    let geocoder = GMSGeocoder()
    geocoder.reverseGeocodeCoordinate(coordinate) { response , error in

      //Add this line
      if let address = response!.firstResult() {
        let lines = address.lines! as [String]
        print(lines)

      }
    }
  }



回答4:


Swift Code to get address of the placemark, nicely Formatted

let address = ABCreateStringWithAddressDictionary(placemark.addressDictionary!, false).componentsSeparatedByString("\n").joinWithSeparator(", ")

print(address!)


来源:https://stackoverflow.com/questions/26226602/convert-gps-coordinates-to-a-city-name-address-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!