0

I am using the Google Maps API for IOS and was wondering if there was a way I could retrieve the current location of the device to show on the map as soon as the app loads.

At the moment, when the app loads the current location coordinate object is nil so I cannot set the map camera onto it without the app crashing. Is there a way to get round this without having to set the camera elsewhere and then the user pressing the my location button to move the camera after.

user3536057
  • 219
  • 3
  • 15

2 Answers2

1

To get location from map just use gmsMap.myLocationEnabled = true and google map will do the rest for you. To set camera to your location add key value observer for key myLocation to map by doing so

map.addObserver(self, forKeyPath: "myLocation", options: .New, context: nil)

deinit {
   //dont forget to remove observer 
   mapView.removeObserver(self, forKeyPath: "myLocation")

}

override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {

    if change[NSKeyValueChangeOldKey] == nil {

        let location = change[NSKeyValueChangeNewKey] as CLLocation
        gmsMap.camera = GMSCameraPosition.cameraWithTarget(location.coordinate, zoom: 16)
    }
}
Zell B.
  • 10,266
  • 3
  • 40
  • 49
0

I think this answer will help you: https://stackoverflow.com/a/20994202/4195406

Basically you have to enable myLocation after the mapview is loaded:

dispatch_async(dispatch_get_main_queue(), ^{
    mapView_.myLocationEnabled = YES;
  });
Community
  • 1
  • 1
ztan
  • 6,861
  • 2
  • 24
  • 44