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

时间:2018-07-20 15:13:32

标签: swift xcode mapkit mapkitannotation

即使滚动时,我也想将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)
}
}
}

1 个答案:

答案 0 :(得分:0)

尝试以下代码:

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

编辑:

您需要使用stopUpdatingLocation()方法调用didUpdateLocations

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)
}