从地址 swift 访问坐标
Access to the coordinates from an address swift
您好,我怎样才能访问此块之外的经度和纬度参数?
let geocoder = CLGeocoder()
geocoder.geocodeAddressString(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)")
}
我想在 firebase 中将这两个参数保存为 Float 或 String。谢谢
您可以创建这样的函数:
func getLatAndLong(address : String, competion : @escaping (CLLocationCoordinate2D?) -> ()) {
let geocoder = CLGeocoder()
geocoder.geocodeAddressString(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)")
competion(placemark?.location?.coordinate)
}
}
然后将其命名为:
var location : CLLocationCoordinate2D?
getLatAndLong(address: "pass your address here") { (coordinates) in
self.location = coordinates
}
现在您的 location
变量保存值。
你可以用它来获取纬度和经度
let latitide = location?.latitude
let longitude = location?.longitude
选项 2
您可以在 class 中声明一个变量,并在获得坐标后更新其值。我建议使用上述方法,因为地理编码器异步运行。最好使用完成处理程序来了解 geoCoder 何时完成任务并获得位置。
var latitude = 0.0 //
var longitude = 0.0
let geocoder = CLGeocoder()
geocoder.geocodeAddressString("address") { placemarks, error in
let placemark = placemarks?.first
self.latitude = placemark?.location?.coordinate.latitude ?? 0.0
self.longitude = placemark?.location?.coordinate.longitude ?? 0.0
}
您好,我怎样才能访问此块之外的经度和纬度参数?
let geocoder = CLGeocoder()
geocoder.geocodeAddressString(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)")
}
我想在 firebase 中将这两个参数保存为 Float 或 String。谢谢
您可以创建这样的函数:
func getLatAndLong(address : String, competion : @escaping (CLLocationCoordinate2D?) -> ()) {
let geocoder = CLGeocoder()
geocoder.geocodeAddressString(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)")
competion(placemark?.location?.coordinate)
}
}
然后将其命名为:
var location : CLLocationCoordinate2D?
getLatAndLong(address: "pass your address here") { (coordinates) in
self.location = coordinates
}
现在您的 location
变量保存值。
你可以用它来获取纬度和经度
let latitide = location?.latitude
let longitude = location?.longitude
选项 2
您可以在 class 中声明一个变量,并在获得坐标后更新其值。我建议使用上述方法,因为地理编码器异步运行。最好使用完成处理程序来了解 geoCoder 何时完成任务并获得位置。
var latitude = 0.0 //
var longitude = 0.0
let geocoder = CLGeocoder()
geocoder.geocodeAddressString("address") { placemarks, error in
let placemark = placemarks?.first
self.latitude = placemark?.location?.coordinate.latitude ?? 0.0
self.longitude = placemark?.location?.coordinate.longitude ?? 0.0
}