Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Mapkit - Move Away From User Location

I want to display user location and the surrounding area, but I also want to allow the user to pan around the area. Right now if I try to scroll somewhere else on the map it automatically takes me back to the base region with the user at the center. How do I stop this? I want to show the initial view with the user in the center, but I want to be able to scroll around too. Thanks in advance you guys are so helpful!

import UIKit import MapKit import 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)
}
like image 471
Murph Avatar asked Feb 10 '15 19:02

Murph


2 Answers

Your code in didUpdateLocations is resetting the region. You have two options.

  1. Store in an ivar whether or not you have already set the first location. Only if you haven't do you then set the region.

  2. Set a timer that runs for 15 seconds. If the map is moved by the user you reset the timer. When the timer expires you can recenter to the users location.

This will keep the map centred around the user but will enable them to pan around a bit to get some context.

This answer shows how to do it in Objective-C

like image 79
Onato Avatar answered Oct 22 '22 08:10

Onato


locationManager.stopUpdatingLocation();

this is all you need at end of locationManager fun, if you are still looking for

like image 23
Beichen FU Avatar answered Oct 22 '22 08:10

Beichen FU