在 Apple 文档 setUserTrackingMode:animated:
据称:
将跟踪模式设置为 MKUserTrackingModeFollow 或 MKUserTrackingModeFollowWithHeading 会使 map View 将 map 置于该位置的中心并开始跟踪用户的位置。如果 map 缩小, map View 自动放大 在用户的位置上,有效地改变当前的可见区域。
我的问题是,有没有一种方法可以在设置用户跟踪模式的同时保留 map 上的当前缩放级别?
最佳答案
我能够做到这一点的方法是调用使用用户位置和中心的 MKCoordinateRegionMakeWithDistance 调用。我用 5000 作为我的值(value)观。这就是我的测试代码的样子。 `导入UIKit
导入核心位置
导入 MapKit
class ViewController: UIViewController, CLLocationManagerDelegate{
@IBOutlet weak var mapView: MKMapView!
var locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
if (CLLocationManager.locationServicesEnabled()){
mapView.showsUserLocation = true
mapView.mapType = MKMapType.satellite
mapView.setUserTrackingMode(MKUserTrackingMode.followWithHeading, animated: true)
//locationManager = CLLocationManager()
//locationManager.delegate = self
//locationManager.desiredAccuracy = kCLLocationAccuracyBest
//locationManager.requestAlwaysAuthorization()
//locationManager.startUpdatingLocation()
}
}
/*func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
let location = locations.last as! CLLocation
let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
//let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
let region = MKCoordinateRegionMakeWithDistance(center, 500, 500)
self.mapView.setRegion(region, animated: true)
}*/
@IBAction func centerButton(_ sender: UIButton, forEvent event: UIEvent) {
let location = MKUserLocation()
let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
let region = MKCoordinateRegionMakeWithDistance(center, 5000, 5000)
self.mapView.setRegion(region, animated: true)
mapView.setUserTrackingMode(MKUserTrackingMode.followWithHeading, animated: true)
}
}
`
不要阅读任何注释掉的 locationManager 信息。这里重要的是要记住,调用 setUserTrackingMode 不会影响缩放级别,而只是将中心移动到用户位置,因此如果您使用区域和距离方法设置缩放级别,然后调用 setUserTrackingMode 它将假定缩放。这使我可以在每次重新定位并跟踪用户当前位置时始终缩小到合理的缩放级别。
关于ios - 将UserTrackingMode 设置为 MKUserTrackingModeFollow 而不更改缩放级别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28169356/