首页 > 解决方案 > 每次我从当前位置滚动时,MapKit 都会自动缩放回当前位置

问题描述

我在 X-code 中构建了一个基本应用程序,它显示用户的位置并自动放大到用户的位置。我希望能够在地图上移动,因为我将在用户位置周围设置重要的注释,但是每次我导航到地图的不同部分时,我都会被拖回放大的位置。有人建议我“处理地图上的平移手势,当地图处于平移状态时不要缩放。您可以使用简单的布尔标志来控制是否缩放。 ”请告知如何解决此问题。

import UIKit

导入 MapKit 导入 CoreLocation

类视图控制器:UIViewController,CLLocationManagerDelegate,MKMapViewDelegate {

@IBOutlet weak var mapView: MKMapView!
private let locationManager = CLLocationManager()


override func viewDidLoad() {
    super.viewDidLoad()
    
    //delegates
    locationManager.delegate = self
    self.mapView.delegate = self
    
    
    locationManager.requestWhenInUseAuthorization()
    
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.distanceFilter = kCLDistanceFilterNone
    
    locationManager.startUpdatingLocation()
    
    self.mapView.showsUserLocation = true
}


//zoom
func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) {
    let region = MKCoordinateRegion(center: mapView.userLocation.coordinate, span: MKCoordinateSpan(latitudeDelta: 0.2, longitudeDelta: 0.2))
    mapView.setRegion(region, animated: true)
}

}

标签: swiftmapkituigesturerecognizer

解决方案


Not sure if you got your answer yet but here is how I took care of it.

I simply added a var called tracking which is set to true at start. I called the locationManager.stopUpdatingLocation() inside my viewDidLoad, then set the tracking variable to false.

super.viewDidLoad()
checkLocationServices()
    
customers = ReadTextFile()
for customer in customers {
    addCustomPin(customer:customer)
}
locationManager.stopUpdatingLocation()
tracking = false

Inside my checkLocationServices(), which calls checkLocationAuthorization() I added

if tracking {
    locationManager.startUpdatingLocation()
}

This way, the first time the app calls the checkLocationServices, my tracking var is true, so it checks for the location.

If I wanted to turn the setting back ON, I just need to turn the variable back to true.


推荐阅读