用户定位焦点 SwiftUI

问题描述

我正在尝试编写一个 Todo 应用程序,并希望将整个应用程序设计为一张地图,其中 Todo 列表上的各个点显示为大头针,并且每次到达这些大头针中的一个时都应执行一个事件.为了测试整个过程,我采用了一个 GPS 轨迹,该轨迹应该模拟乘坐公交车,并向我的应用程序提供 GPS 数据。各个点都在此 GPS 轨道上。

我的应用有一个按钮,当您按下它时,它始终聚焦于用户位置。问题是他总是关注 GPS 轨迹的起点,而不是 GPS 轨迹的当前位置。

非常感谢您的帮助!

这是焦点函数和位置更新函数

@Published var region : MKCoordinateRegion!

func focusLocation() {
        
   guard let _ = region else{return}
        
   mapView.setRegion(region,animated: true)
   mapView.setVisibleMapRect(mapView.visibleMapRect,animated: true)
}

func locationManager(_ manager: CLLocationManager,didUpdateLocations locations: [CLLocation]) {
   guard let location = locations.last else{return}
   self.region = MKCoordinateRegion(center: location.coordinate,latitudinalMeters: 10000,longitudinalMeters: 10000)
        
   self.mapView.setRegion(self.region,animated: true)
   self.mapView.setVisibleMapRect(self.mapView.visibleMapRect,animated: true)
}


解决方法

当您按下按钮时,您可以尝试这样的操作,因为您有要关注的坐标:

func focusLocation(gotoLocation: CLLocationCoordinate2D) {
    let rangeInMeters: Double = 10000   // <-- adjust as desired
    let coordinateRegion = MKCoordinateRegion.init(center: gotoLocation,latitudinalMeters: rangeInMeters,longitudinalMeters: rangeInMeters)
    mapView.setRegion(coordinateRegion,animated: true)
}