Reputation: 1822
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.
Upvotes: 3
Views: 1831
Reputation: 2084
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.
Upvotes: 1
Reputation: 1822
With help from Sunil's answer above, I figured out how to solve this problem.
Sunil notes that the app calls observeValue()
every time the user's location is updated. So based off of the code I had in observeValue()
this would make sense that the mapView
camera would update every time the user's location updates.
I solved the problem by moving
self.mapView.camera = GMSCameraPosition.camera(withTarget: myLocation.coordinate, zoom: 14)
to another function like viewDidAppear()
.
Some may ask why I didn't move it to viewDidLoad()
as that is called before viewDidAppear()
. The app doesn't fetch the user's location until the end of viewDidLoad()
. So putting the camera declaration at the end of the viewDidLoad()
doesn't give the app enough time to fetch the users location. By declaring the camera position in the viewDidAppear()
function, we give the app ample time to process the user's location and fetch it.
Note: Make sure to pass your location variable out of the observeValue()
function for use in viewDidAppear()
.
Upvotes: 0