Swift Mapkit - 远离用户位置

Mur*_*rph 8 xcode mapkit ios swift

我想显示用户位置和周围区域,但我也希望允许用户在该区域内平移.现在,如果我尝试在地图上的其他位置滚动,它会自动将我带回到基本区域,用户位于中心.我怎么阻止这个?我想在中心显示用户的初始视图,但我希望能够滚动.在此先感谢您们的帮助!

导入UIKit导入MapKit导入CoreLocation

class ViewControllerMain:UIViewController,MKMapViewDelegate,CLLocationManagerDelegate {

@IBOutlet weak var mapView: MKMapView!

var locationManager:CLLocationManager!

override func viewDidLoad() {
    super.viewDidLoad()
    locationManager = CLLocationManager()
    locationManager.requestWhenInUseAuthorization()
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.delegate = self
    locationManager.startUpdatingLocation()
    mapView.showsUserLocation = true
    mapView.delegate = self

    let longPress = UILongPressGestureRecognizer(target: self, action: "action:")
    longPress.minimumPressDuration = 1.0
    mapView.addGestureRecognizer(longPress)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
    let regionToZoom = MKCoordinateRegionMake(manager.location.coordinate, MKCoordinateSpanMake(0.01, 0.01))
    mapView.setRegion(regionToZoom, animated: true)
}
Run Code Online (Sandbox Code Playgroud)

Ona*_*ato 6

您在didUpdateLocations中的代码正在重置该区域.你有两个选择.

  1. 无论您是否已经设置了第一个位置,都要存放在ivar中.只有你没有这样做,然后设置区域.

  2. 设置一个运行15秒的计时器.如果用户移动了地图,则重置计时器.当计时器到期时,您可以重新定位到用户位置.

这将使地图以用户为中心,但会使他们平移一点以获得一些上下文.

这个答案显示了如何在Objective-C中完成它