Search code examples
swiftmapsgoogle-maps-sdk-iosgoogle-directions-api

How to make my Google Map follow the user at all times and not let them scroll away


I have a GMSMapView connected to my mapView variable. It is all set up and even puts a random polyline on the map for the user. Currently I have a "navigate" button but all it does is zoom in on the user. I would like to make it so once they hit "navigate" it will make the camera follow the user and not let them scroll away from their location (much like the Google Maps app). How can I make this possible? Thanks!


Solution

  • I'm assuming you've already gotten a CLLocationManager and have started updating user's location with it. Once that's done, you want to set the mapView's camera in the CLLocationManager's delegate method whenever the location changes.

    Something along the lines of this:

    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if let location = manager.location {
            // Create camera with the user's new location
            let camera = GMSCameraPosition.cameraWithLatitude(location.coordinates.latitude, longitude: location.coordinates.longitude, zoom: 17.0)
            // Animate the map to the new camera position
            mapView.animateToCameraPosition(camera)
        }
    }
    

    Play around with the zoom parameters to get the result you desire.

    Hope it helps.