Reputation: 1519
I'm trying to get the current position of the device using Google Maps SDK in Xamarin.iOS, I got the following code but I'm getting an exception.
I've imported the Google Maps SDK for iOS in Xamarin
using Google.Maps;
This is my code:
MapView gmapView;
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
CameraPosition camera = CameraPosition.FromCamera (latitude: 40.7056308,
longitude: -73.9780035,
zoom: 13);
mapView = MapView.FromCamera (new RectangleF(0, 0, View.Frame.Width, View.Frame.Bottom - 50), camera);
mapView.Settings.CompassButton = true;
mapView.Settings.MyLocationButton = true;
// Listen to the myLocation property of GMSMapView.
mapView.AddObserver (this, new NSString ("myLocation"), NSKeyValueObservingOptions.New, IntPtr.Zero);
// More code ...
// ...
// Ask for My Location data after the map has already been added to the UI.
InvokeOnMainThread (()=> mapView.MyLocationEnabled = true);
}
Then I define the method that should be called when the position of the user changes:
public override void ObserveValue (NSString keyPath, NSObject ofObject, NSDictionary change, IntPtr context)
{
if (!firstLocationUpdate) {
// If the first location update has not yet been recieved, then jump to that
// location.
firstLocationUpdate = true;
var location = change.ObjectForKey (NSValue.ChangeNewKey) as CLLocation;
mapView.Camera = CameraPosition.FromCamera (location.Coordinate, 14);
}
}
But I'm getting the following exception and have been stuck with this for a while with no luck :/
MonoTouch.Foundation.MonoTouchException: Objective-C exception thrown. Name: NSInternalInconsistencyException Reason: <MapViewController: 0x1b6648c0>: An - observeValueForKeyPath:ofObject:change:context: message was received but not handled.
Upvotes: 0
Views: 1492
Reputation: 52
I've run into the same problem, was trying everything but nothing helped. Mayber there is some bug in Xamarin's Google Maps library.
Finally I've rewritten the observer
to timer
. It's ugly but it's working for now.
NSRunLoop.Main.AddTimer (NSTimer.CreateRepeatingTimer (0.2d, (timer) => {
var location = mapView.MyLocation;
if (location == null) {
return;
} else {
timer.Invalidate ();
}
//do what you need with current location
}), NSRunLoopMode.Default);
Upvotes: 0
Reputation: 770
Try to move this line
mapView.AddObserver (this, new NSString ("myLocation"), NSKeyValueObservingOptions.New, IntPtr.Zero);
Inside the InvokeOnMainThread, like this:
InvokeOnMainThread (()=> {
mapView.MyLocationEnabled = true;
mapView.AddObserver (this, new NSString ("myLocation"), NSKeyValueObservingOptions.New, IntPtr.Zero);
});`
Upvotes: 1