Search code examples
mapboxmapbox-ios

how to keep map always centred with current location while zooming in zooming out in MapBox iOS


I am implementing Map-box sdk in iOS. So my requirement is that when user zooms in or out or rotate the map.. the users location should always be in centre..

Is there any method or API available to achieve this functionality ?


Solution

  • You can use the MGLMapView property isScrollEnabledand set it to false.

    mapView.isScrollEnabled = false
    

    That stops scrolling but still allows the user to double tap the map and zoom to another location and pinch to zoom. To stop both of these from changing the center location you would use the following delegate method:

    optional func mapView(_ mapView: MGLMapView, shouldChangeFrom oldCamera: MGLMapCamera, to newCamera: MGLMapCamera) -> Bool
    

    Something like the code below works but it assumes that you have already centered the map on the user location. Also note the ! on the user's location... please make the usual safety checks in your actual app.

    func mapView(_ mapView: MGLMapView, shouldChangeFrom oldCamera: MGLMapCamera, to newCamera: MGLMapCamera) -> Bool {
        newCamera.centerCoordinate = mapView.userLocation!.coordinate
        mapView.camera = newCamera
    
        return true
    }
    

    Hope this helps.