gpt4 book ai didi

ios - 为什么第二个 MKPointAnnotation 不显示?

转载 作者:行者123 更新时间:2023-11-30 12:52:33 25 4
gpt4 key购买 nike

我正在尝试在 MapView 上显示两个注释。

为什么第二个注释不显示在 MapView 中?我尝试将地标[0]更改为放置标记[1],但没有帮助。

我本来可以使用 for 子句,但为了测试我重复了代码。

class Asiakas {
var nimi = ""
var osoite = ""

init(nimi: String, osoite: String) {
self.nimi = nimi
self.osoite = osoite
}
}


class ViewController: UIViewController {

@IBOutlet weak var mapView: MKMapView!

var asiakkaat:[Asiakas] = [
Asiakas(nimi: "Testi Asiakas", osoite: "Museokatu 10, helsinki"),
Asiakas(nimi: "Hyvä asiakas", osoite: "Pihlajatie 17, helsinki")
]

var asiakas:Asiakas!


override func viewDidLoad() {
super.viewDidLoad()

let geoCoder = CLGeocoder()

geoCoder.geocodeAddressString(asiakkaat[0].osoite, completionHandler: { placemarks, error in
if error != nil {
print(error)
return
}

if let placemarks = placemarks {
let placemark = placemarks[0]

let annotation = MKPointAnnotation()
if let location = placemark.location {
annotation.coordinate = location.coordinate
self.mapView.addAnnotation(annotation)
}
}
})

geoCoder.geocodeAddressString(asiakkaat[1].osoite, completionHandler: { placemarks, error in
if error != nil {
print(error)
return
}

if let placemarks = placemarks {
let placemark = placemarks[0]

let annotation = MKPointAnnotation()
if let location = placemark.location {
annotation.coordinate = location.coordinate
self.mapView.addAnnotation(annotation)
}
}
})

}

最佳答案

您无法同时调用多个地理编码服务。

来自geocodeAddressString(_ addressString: String,completionHandler: CoreLocation.CLGeocodeCompletionHandler)的文档:

Submits a forward-geocoding request using the specified string. This method submits the specified location data to the geocoding server asynchronously and returns. Your completion handler block will be executed on the main thread. After initiating a forward-geocoding request, do not attempt to initiate another forward- or reverse-geocoding request.

因此,您需要在第一个调用完成后进行第二个调用。

如果您这样做,您将得到正确的结果:

let geoCoder = CLGeocoder()

geoCoder.geocodeAddressString(asiakkaat[0].osoite, completionHandler: { placemarks, error in
if error != nil {
print(error)
return
}

geoCoder.geocodeAddressString(self.asiakkaat[1].osoite, completionHandler: { placemarks, error in
if error != nil {
print(error)
return
}

if let placemarks = placemarks {
let placemark = placemarks[0]

let annotation = MKPointAnnotation()
if let location = placemark.location {
annotation.coordinate = location.coordinate
self.mapView.addAnnotation(annotation)
}
}
})

if let placemarks = placemarks {
let placemark = placemarks[0]

let annotation = MKPointAnnotation()
if let location = placemark.location {
annotation.coordinate = location.coordinate
self.mapView.addAnnotation(annotation)
}
}
})

关于ios - 为什么第二个 MKPointAnnotation 不显示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40789433/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com