我正在尝试将CLLocationCoordinates2d坐标转换为实际街道地址。
我没有运气就尝试过CLGeocoder。这是我的代码,提供了纬度和经度坐标。
let manager = CLLocationManager()
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
guard let locValue: CLLocationCoordinate2D = manager.location?.coordinate else { return }
print("locations = \(locValue.latitude) \(locValue.longitude)")
// let locationtext = "locations = \(locValue.latitude) \(locValue.longitude)"
locationTxt.text = "\(locValue.latitude) \(locValue.longitude)"
}
谢谢!
答案 0 :(得分:2)
是的,您可以从协调中心获取街道地址,因为您需要以下代码
func getAddressFromLatLon(Latitude: Double, Longitude: Double) {
var center : CLLocationCoordinate2D = CLLocationCoordinate2D()
let ceo: CLGeocoder = CLGeocoder()
center.latitude = Latitude
center.longitude = Longitude
let loc: CLLocation = CLLocation(latitude:center.latitude, longitude: center.longitude)
ceo.reverseGeocodeLocation(loc, completionHandler:
{(placemarks, error) in
if (error != nil)
{
print("reverse geodcode fail: \(error!.localizedDescription)")
}
let pm = placemarks! as [CLPlacemark]
if pm.count > 0 {
let pm = placemarks![0]
print(pm.country)
print(pm.locality)
print(pm.subLocality)
print(pm.thoroughfare)
print(pm.postalCode)
print(pm.subThoroughfare)
var addressString : String = ""
if pm.subLocality != nil {
addressString = addressString + pm.subLocality! + ", "
}
if pm.thoroughfare != nil {
addressString = addressString + pm.thoroughfare! + ", "
}
if pm.locality != nil {
addressString = addressString + pm.locality! + ", "
}
if pm.country != nil {
addressString = addressString + pm.country! + ", "
}
if pm.postalCode != nil {
addressString = addressString + pm.postalCode! + " "
}
print(addressString)
}
})
}
调用此函数并传递参数即可获取地址字符串。如果不起作用,请发表评论,以便我进一步指导您。
答案 1 :(得分:2)
func convertLatLongToAddress(latitude:Double,longitude:Double){
let geoCoder = CLGeocoder()
let location = CLLocation(latitude: latitude, longitude: longitude)
geoCoder.reverseGeocodeLocation(location, completionHandler: { (placemarks, error) -> Void in
// Place details
var placeMark: CLPlacemark!
placeMark = placemarks?[0]
// Location name
if let locationName = placeMark.location {
print(locationName)
}
// Street address
if let street = placeMark.thoroughfare {
print(street)
}
// City
if let city = placeMark.subAdministrativeArea {
print(city)
}
// Zip code
if let zip = placeMark.isoCountryCode {
print(zip)
}
// Country
if let country = placeMark.country {
print(country)
}
})
}