gpt4 book ai didi

ios - Mapkit,如何将注释坐标更改为最近的地址?

转载 作者:行者123 更新时间:2023-11-30 11:06:04 24 4
gpt4 key购买 nike

我正在开发一个导航应用程序,它的一个用途是它可以计算用户放置的所有注释坐标的平均值(通过搜索表,并且当他们按下结果时放置每个注释) )并在所有注释之间找到您所谓的中间点。然而,这个中点目前仅通过坐标,这意味着根据用户当前注释的位置,这个中点可能会出现在湖泊或森林的中间,这是没有帮助的。我希望它找到距离我的中点坐标最近的地址,并将注释重定向到那里。以下是创建注释的方法:

@IBAction func middleFinderButton(_ sender: Any) {

let totalLatitude = mapView.annotations.reduce(0) { $0 + $1.coordinate.latitude }

let totalLongitude = mapView.annotations.reduce(0) { $0 + $1.coordinate.longitude }

let averageLatitude = totalLatitude/Double(mapView.annotations.count)

let averageLongitude = totalLongitude/Double(mapView.annotations.count)

let centerPoint = MKPointAnnotation()

centerPoint.coordinate.latitude = averageLatitude
centerPoint.coordinate.longitude = averageLongitude

mapView.addAnnotation(centerPoint)
}

如何让这个注释“centerPoint”调整到最近的地址?谢谢。

最佳答案

我将在这里使用反向地理编码返回 MKPlacemark。 documentation建议完成处理程序通常在主线程上仅返回一个地标,因此您可以立即使用结果来更新 UI。 MKPlacemark 符合注释协议(protocol),因此您可以直接将其放在 map 上:

func resolveAddress(for averageCoordinate: CLLocationCoordinate2D, completion: @escaping (MKPlacemark?) -> () ) {

let geocoder = CLGeocoder()
let averageLocation = CLLocation(latitude: averageCoordinate.latitude, longitude: averageCoordinate.longitude)
geocoder.reverseGeocodeLocation(averageLocation) { (placemarks, error) in
guard error == nil,
let placemark = placemarks?.first
else {
completion(nil)
return
}
completion(MKPlacemark(placemark: placemark))
}
}

@IBAction func middleFinderButton(_ sender: Any) {

// your code to find center annotation

resolveAddress(for: centerPoint.coordinate) { placemark in
if let placemark = placemark {
self.mapView.addAnnotation(placemark)
} else {
self.mapView.addAnnotation(centerCoordinate)
}
}

关于ios - Mapkit,如何将注释坐标更改为最近的地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52710145/

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