c# - Xamarin iOS Google Maps SDK - mapView.AddObserver() 异常

标签 c# ios google-maps xamarin.ios xamarin

我尝试在 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/

相关文章:

c# - 如何在 C# 中的 SQL 查询中包含变量

c# - CSV Helper 解析器抛出 IOException。无法从传输连接读取数据

iOS - UIImage 调整到更大变得模糊

ios - UIWebView 嵌入视频回调在 iOS8 中不起作用?

android - 不对称 map 标记

c# - 如何使用接口(interface)使 MainPage.xaml.cs 与 MainActivity.cs 对话

c# - 使用 Where 子句返回子代

ios - NSLog 检测更新 MKPolygon 中的当前位置

ajax - 除 Google 之外,您还使用哪些 Maps API 与 GWT?

javascript - 在 Google map 标记上显示信息