KMC
KMC

Reputation: 1742

How do you centre the map as user changes location

How do you center the google map as user is moving, like driving? The code I have does not center the user, and the user just goes toward the border and disapper. How do you keep user in center all the time?

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    if let location = manager.location {

        if (firstLoad) {
            firstLoad = false
            recentCoordinate = location.coordinate
            mapView.camera = GMSCameraPosition(target: location.coordinate, zoom: Constants.MapView.Zoom, bearing: 0, viewingAngle: Constants.MapView.ViewingAngle)
        }
        else {
             // This line of code suppose to center the user as user moves along while keeping the zoom and angle state user has chosen
             mapView.camera = GMSCameraPosition(target: location.coordinate, zoom: mapView.camera.zoom, bearing: 0, viewingAngle: mapView.camera.viewingAngle)


        }

        // Filter out noise. Currently not working
        let age = 0 - location.timestamp.timeIntervalSinceNow
        if (age > 120) {
            return;    // ignore old (cached) updates
        }
        if (location.horizontalAccuracy < 0) {
            return;   // ignore invalid updates
        }

        if (location.horizontalAccuracy <= 10){
            // this is a valid update
            // Draw route as user moves along
            path.addCoordinate(CLLocationCoordinate2D(latitude: location.coordinate.latitude,
                longitude: location.coordinate.longitude))
            let polyline = GMSPolyline(path: path)
            polyline.strokeColor = UIColor.redColor()
            polyline.strokeWidth = 3
            polyline.map = mapView

            // Save the coordinates to array
            coordinateArray.append([location.coordinate.latitude, location.coordinate.longitude])



        }
     }

Upvotes: 0

Views: 1733

Answers (2)

KMC
KMC

Reputation: 1742

If anybody looking for swift 2.3 solution like myself, here is the solution :

mapView.animateToLocation(CLLocationCoordinate2D(latitude: location.coordinate.latitude,longitude: location.coordinate.longitude))

Upvotes: 0

Ryan
Ryan

Reputation: 4884

There are couple other ways you can try.

let update = GMSCameraUpdate.setTarget(location.coordinate)
mapView.moveCamera(update)

or

mapView.camera = GMSCameraPosition.camera(target: location.coordinate, zoom: 15.0)

or

let update = GMSCameraUpdate.setTarget(location.coordinate)
        mapView.animate(with: update)

Upvotes: 1

Related Questions