gpt4 book ai didi

swift - 如何在 mapkit 中获取到最近引脚的方向

转载 作者:行者123 更新时间:2023-11-28 05:45:51 25 4
gpt4 key购买 nike

我正在尝试获取从用户当前位置到最近的图钉的方向

-我的代码是

 let locationManager = CLLocationManager()
var currentCoordinate: CLLocationCoordinate2D!

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let pins = mapView?.annotations
// let currentLocation = mapView?.userLocation.location
guard let currentLocation = locations.first else { return }
currentCoordinate = currentLocation.coordinate
let nearestPin: MKAnnotation? = pins!.reduce((CLLocationDistanceMax,nil)) { (nearest, pin) -> (CLLocationDistance, MKAnnotation) in
let coord = pin.coordinate
let loc = CLLocation(latitude: coord.latitude, longitude: coord.longitude)
let distance = currentLocation.distance(from: loc)
print(distance, pin)
return distance < nearest.0 ? (distance, pin) : nearest as! (CLLocationDistance, MKAnnotation)
} as AnyObject as? MKAnnotation
if nearestPin?.title == "Test"{
print("found")
}
}

但效果不是很好

谢谢

最佳答案

首先,检查您是否在Info.plist 中设置了Location Privacy。在你的情况下,我检查了扩展中的授权。

CLLocationManagerDelegate

extension ViewController: CLLocationManagerDelegate{
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
checkLocationAuthorization()
}

不要忘记在 viewDidLoad()

中设置委托(delegate)

委托(delegate)
locationManager.delegate = self

现在进入实际问题。我创建了一个可以调用的私有(private)函数

 locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])

搜索最近的注释

我猜您声明了一组注释 (var annotation = [MKAnnotation]())。我们将使用这些注释(在我的例子中是巴黎和阿姆斯特丹)与我们当前的位置进行比较以找到最近的位置。

    private func getNearestPin(locations: [CLLocation]) -> MKAnnotation? {

let allPinsOnMap = mapView?.annotations

guard let currentLocation = locations.first else { return nil }
if let pins = allPinsOnMap {

let nearestPin: (CLLocationDistance, MKAnnotation?) = pins.reduce((CLLocationDistanceMax,nil))
{ (nearest, pin) -> (CLLocationDistance, MKAnnotation?) in
let coord = pin.coordinate
let loc = CLLocation(latitude: coord.latitude, longitude: coord.longitude)
let distance = currentLocation.distance(from: loc)

return distance < nearest.0 ? (distance, pin) : nearest
}
return nearestPin.1

}
return nil
}


该函数将返回一个 MKAnnotation?,因此当我们调用该函数时,我们必须检查它是否不返回 nil。我们在我们的扩展中调用这个函数!

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let nearest = getNearestPin(locations: locations) {
if nearest.title == "Amsterdam" {
print("Nearest is available: \(nearest.title! ?? "Title")")
}
}
}

如果您有任何进一步的问题或反馈,请告诉我!

关于swift - 如何在 mapkit 中获取到最近引脚的方向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54808643/

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