即使在滚动时也将 MKPointAnnotation 修复到 MapKit 的中心

Fix MKPointAnnotation to centre of MapKit even while scrolling

我想在滚动时将 MKPointAnnotation 固定到地图的中心,我尝试这样做但是 MKPointAnnotation 在滚动时没有移动 这是我的代码:

import UIKit
import MapKit

class HomeVC: UIViewController,MKMapViewDelegate,CLLocationManagerDelegate {

@IBOutlet var myMap: MKMapView!
private var locationManager = CLLocationManager();
private var userLocation: CLLocationCoordinate2D?;
//    private var riderLocation: CLLocationCoordinate2D

override func viewDidLoad() {
super.viewDidLoad()
initializeLocationManager()}

// find location on the map
private func initializeLocationManager(){
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()}

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

// if we hade the coordinate from the manager
if let location = locationManager.location?.coordinate {
userLocation = CLLocationCoordinate2D(latitude: location.latitude, longitude: location.longitude)
// the place the map will show (ZOOM LVL ON MAP)
let region = MKCoordinateRegion(center: userLocation!, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
myMap.setRegion(region, animated: true)

//To Remove annotation = Point on map befor add new one
myMap.removeAnnotations(myMap.annotations)

//Show My Point At Map
let annotation = MKPointAnnotation();
annotation.coordinate = myMap.centerCoordinate
myMap.addAnnotation(annotation)
}
}
}

试试下面的代码:

// Show My Point At Map
let annotation = MKPointAnnotation()
annotation.coordinate = myMap.region.center // instead of myMap.centerCoordinate
myMap.addAnnotation(annotation)

编辑:

您需要在 didUpdateLocations 方法中调用 stopUpdatingLocation()

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

    // if we hade the coordinate from the manager
    if let location = locationManager.location?.coordinate {
        userLocation = CLLocationCoordinate2D(latitude: location.latitude, longitude: location.longitude)
        // the place the map will show (ZOOM LVL ON MAP)
        let region = MKCoordinateRegion(center: userLocation!, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
        myMap.setRegion(region, animated: true)
        locationManager.stopUpdatingLocation() // <- Stop updating
    }
}

并且你应该使用 regionDidChangeAnimated 方法使 MKPointAnnotation 即使在滚动时也固定在地图的中心,

func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
    // To Remove annotation = Point on map befor add new one
    myMap.removeAnnotations(myMap.annotations)

    let annotation = MKPointAnnotation();
    annotation.coordinate = myMap.region.center
    myMap.addAnnotation(annotation)
}