我正在尝试使用geocoders geocodeAddressString函数向mappview添加多个注释。
问题是,它只添加了其中一个,evn,尽管它告诉我这两个都在运行。。
这是我的代码-顺便说一句,我以前从来没有真正使用过递归,所以如果我做错了,请纠正我!:)
func geoCode(addresses: [String]) {
print("Addresser: \(addresses.count)")
guard let address = addresses.first else {
print("No more adresses :) - returning")
return
}
print("3333 address: \(address)")
dispatch_async(dispatch_get_main_queue()) {
self.geocoder.geocodeAddressString(address) { (placemarks, error) in
print("In geocoder!")
if error == nil {
if let placemark = (placemarks?[0])! as? CLPlacemark {
self.annotation.coordinate = CLLocationCoordinate2DMake((placemark.location?.coordinate.latitude)!, (placemark.location?.coordinate.longitude)!)
self.map.addAnnotation(self.annotation)
let remainingAddresses = Array(addresses[1..<addresses.count])
print("addresses left: \(remainingAddresses.count)")
self.geoCode(remainingAddresses)
}
}
}
}
}
这是我的控制台输出:
Addresser: 2
3333 address: Kastrupvej 2A 2300 København s
In geocoder!
addresses left: 1
Addresser: 1
3333 address: Holmbladsgade 20 2300 København S
In geocoder!
addresses left: 0
Addresser: 0
No more adresses :) - returning
但我的地图上只有一个注解,这是最后一个。。
有人能告诉我为什么,我做错了什么吗?:)
我先尝试了for循环,但地理编码器一次只能处理一件事——这就是为什么我尝试了异步和递归方法。
祝你今天愉快!
最佳答案
尝试每小时分配一次地理编码器。
调用geocoder.cancelGeocode()方法。
这样地:
func geoCode(addresses: [String]) {
print("Addresser: \(addresses.count)")
guard let address = addresses.first else {
print("No more adresses :) - returning")
return
}
print("3333 address: \(address)")
dispatch_async(dispatch_get_main_queue()) {
let geocoder = CLGeocoder()
geocoder.geocodeAddressString(address) { (placemarks, error) in
print("In geocoder!")
if error == nil {
if let placemark = (placemarks?[0])! as? CLPlacemark {
self.annotation.coordinate = CLLocationCoordinate2DMake((placemark.location?.coordinate.latitude)!, (placemark.location?.coordinate.longitude)!)
self.map.addAnnotation(self.annotation)
let remainingAddresses = Array(addresses[1..<addresses.count])
print("addresses left: \(remainingAddresses.count)")
self.geoCode(remainingAddresses)
}
geocoder.cancelGeocode()
}
}
}
}
关于ios - 使用geocoder.geocodeAddressString添加多个注释(递归?),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42715461/