移动地图视图相机时更新纬度和经度?

Update lat and long when the mapview camera is being moved?

这是我的代码,它可以工作,但没有更新而且不准确。我只是想将相机纬度和经度应用于另一个变量。

let cameraLat = self.mapView.camera.centerCoordinate.latitude
let cameraLng = self.mapView.camera.centerCoordinate.longitude

对于 google 地图:

如果您设置了 mapView.delegate = self 并且实现了 GMSMapViewDelegate,那么每次相机改变时都可以很容易地获得一个事件,因此您的 mapView 视图也会改变。

您可以实施 func mapView(mapView: GMSMapView, didChangeCameraPosition position: GMSCameraPosition)func mapView(mapView: GMSMapView, idleAtCameraPosition position: GMSCameraPosition) 方法。

然后像以前一样访问新的相机值 (lat/lng),因此只需将变量重新分配给新值即可。

或 MapKit:

将委托添加到 class 喜欢

class ViewController: UIViewController, MKMapViewDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        ...
        mapView.delegate = self
    }
}

This method is called whenever the currently displayed map region changes. During scrolling, this method may be called many times to report updates to the map position. Therefore, your implementation of this method should be as lightweight as possible to avoid affecting scrolling performance.

func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
   let lat = mapView.camera.centerCoordinate.latitude
   let lng = mapView.camera.centerCoordinate.longitude
}