我尝试在 Xamarin.iOS 中使用 Google Maps SDK 获取设备的当前位置,我得到了以下代码,但遇到了异常。
我已在 Xamarin 中导入适用于 iOS 的 Google Maps SDK
using Google.Maps;
这是我的代码:
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);
}
然后我定义当用户位置改变时应该调用的方法:
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);
}
}
但是我遇到了以下异常,并且已经坚持了一段时间但没有运气:/
MonoTouch.Foundation.MonoTouchException: Objective-C exception thrown. Name: NSInternalInconsistencyException Reason: <MapViewController: 0x1b6648c0>: An - observeValueForKeyPath:ofObject:change:context: message was received but not handled.
最佳答案
尝试移动这条线
mapView.AddObserver (this, new NSString ("myLocation"), NSKeyValueObservingOptions.New, IntPtr.Zero);
在 InvokeOnMainThread 内部,如下所示:
InvokeOnMainThread (()=> {
mapView.MyLocationEnabled = true;
mapView.AddObserver (this, new NSString ("myLocation"), NSKeyValueObservingOptions.New, IntPtr.Zero);
});`
关于c# - Xamarin iOS Google Maps SDK - mapView.AddObserver() 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27316167/