如何从 CLGeocoder geocodeAddressString() 中的完成处理程序更新列表中的地址
Posted
技术标签:
【中文标题】如何从 CLGeocoder geocodeAddressString() 中的完成处理程序更新列表中的地址【英文标题】:How to update address in list from completion handler in CLGeocoder geocodeAddressString() 【发布时间】:2017-03-22 17:48:22 【问题描述】:我有一个要更新的地址列表,还要添加经纬度。将地址列表读入数组后,我调用 CLGeocoder 中的 geocodeAddressString 函数。
在完成处理程序中,我如何知道地址列表中的哪个索引用于进行 geocodeAddressString 调用?
基本上我想设置
locations[1].MailAddr1 = placemark.name
locations[1].MailCity = placemark.locality
locations[1].MailState = placemark.administrativeArea
locations[1].MailZip = placemark.postalCode
locations[1].lat = placemark.location!.coordinate.latitude
locations[1].long = placemark.location!.coordinate.longitude
如何返回位置数组以及如何知道索引,在本例中 = 1?
我希望能够遍历整个数组。
let locations = ReadCSV()
let address = locations[1].MailAddr1 + ", " + locations[1].MailCity + ", " + locations[1].MailState + ", " + locations[1].MailZip + ", " + locations[1].MailCountry
let geocoder = CLGeocoder()
geocoder.geocodeAddressString(address, completionHandler: (placemarks, error) -> Void in
if((error) != nil)
print("Error", error)
if let placemark: CLPlacemark = placemarks?.first
let name = placemark.name
let address = placemark.thoroughfare
let locality = placemark.locality
let zip = placemark.postalCode
let subLocality = placemark.subLocality
let country = placemark.country
let coordinates:CLLocationCoordinate2D = placemark.location!.coordinate
let location: CLLocation = placemark.location!
)
【问题讨论】:
【参考方案1】:我假设你的位置是一个班级:
检查你的数组,然后使用这个位置:
for location in locations
//...
// in your completion handler
location.lat = placemark.location!.coordinate.latitude
//...
PS:如果 location 是一个结构,那么你需要做一个不同的策略
【讨论】:
【参考方案2】:尝试制作函数并将每个位置作为输入参数发送
例子:
for location in locations
setAddressOflocation(location)
func getAddressOflocation (locationObject : inout CLLocation)
let address = locationObject.MailAddr1 + ", " + locationObject.MailCity + ", " + locationObject.MailState + ", " + locationObject.MailZip + ", " + locationObject.MailCountry
let geocoder = CLGeocoder()
geocoder.geocodeAddressString(address, completionHandler: (placemarks, error) -> Void in
if((error) != nil)
print("Error", error)
if let placemark: CLPlacemark = placemarks?.first
let name = placemark.name
let address = placemark.thoroughfare
let locality = placemark.locality
let zip = placemark.postalCode
let subLocality = placemark.subLocality
let country = placemark.country
let coordinates:CLLocationCoordinate2D = placemark.location!.coordinate
let location: CLLocation = placemark.location!
locationObject.lat = placemark.location!.coordinate.latitude
locationObject.long = placemark.location!.coordinate.longitude
)
【讨论】:
以上是关于如何从 CLGeocoder geocodeAddressString() 中的完成处理程序更新列表中的地址的主要内容,如果未能解决你的问题,请参考以下文章