Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop Map Updating on User Location Update - Google Maps iOS SDK

My app starts up at the user's location, however, every time the user moves the map's camera updates to their location. I want it to load to their location, but then allow them to freely browse the map even if their location is moving. Similar to the behavior exhibited in the Google Maps app. I'm using a KVO to gather the location within the viewDidLoad() function. That line looks like this:

mapView.isMyLocationEnabled = true
self.mapView.addObserver(self, forKeyPath: "myLocation", options: NSKeyValueObservingOptions.new, context: nil)

Here's my code of the observe function:

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {

    guard let update = change, let myLocation = update[NSKeyValueChangeKey.newKey] as? CLLocation else {
        print("Location not found")
        return
    }

    self.mapView.camera = GMSCameraPosition.camera(withTarget: myLocation.coordinate, zoom: 14)

}

What needs to change to make it meet the criteria mentioned above.

like image 468
bwc Avatar asked Feb 04 '26 10:02

bwc


1 Answers

Using this helper code, you can get user's location and set the target like:

CLLocationManager *manager = [CLLocationManager updateManagerWithAccuracy:50.0 locationAge:15.0     authorizationDesciption:CLLocationUpdateAuthorizationDescriptionAlways];
    [self.manager startUpdatingLocationWithUpdateBlock:^(CLLocationManager *manager, CLLocation *location, NSError *error, BOOL *stopUpdating) {
    self.mapView.camera = GMSCameraPosition.camera(withTarget: location.coordinate, zoom: 14)
}]; 

If you dont' want to use the above helper code, then you can get user's location using Core Location basic api as well.

Note that your code calls observeValue every time the user's location is changed, that results in setting camera for user's location map.

like image 112
Sunil Chauhan Avatar answered Feb 06 '26 05:02

Sunil Chauhan