2016-08-13 100 views
1

我試圖執行下面的代碼Xamarin形式獲取位置

var locator = CrossGeolocator.Current; 

locator.DesiredAccuracy = 100; //100 is new default 

var position = await locator.GetPositionAsync(timeoutMilliseconds: 10000); 

在Xamarin形式使用Xam.plugin.Geolocator但得到「這個功能是不是在這個大會的便攜式版本中實現。您應該引用來自主應用程序項目的NuGet包,以便參考平臺特定的實現。「異常。

我使用3.0.4版本Xam.plugin.Geolocator從這個鏈接https://www.nuget.org/packages/Xam.Plugin.Geolocator

我已經從飲用水,項目和機器人項目添加NuGet包。加入

[組件:UsesPermission(Android.Manifest.Permission.AccessFineLocation)] [組件:UsesPermission(Android.Manifest.Permission.AccessCoarseLocation)]

在AssemblyInfo.cs中。還確保在Visual Studio 2015中的Android清單中檢查「Access_Coarse_Location」和「Access_Fine_Locations」。

任何人都可以幫助我失蹤?

+0

它看起來像你沒有添加geolocator NuGet插件給你r android項目? –

回答

0

您可以使用依賴注入來訪問原生Android代碼並獲取當前位置。

創建一個類,將等待結果

class GeolocationWaiter : Java.Lang.Object,ILocationListener 
{ 
    private bool done = false; 
    private double latitude = 0; 
    private double longitude = 0; 


    public Task<GeoLocation> getLocation() 
    { 
     return Task<GeoLocation>.Run(() => 
     { 
      while (!done) { } 
      GeoLocation location; 
      location.latitude = latitude; 
      location.longitude = longitude; 
      return location; 
     }); 
    } 

    public void OnLocationChanged(Location location) 
    { 
     Toast.MakeText(Forms.Context, "Update", ToastLength.Long).Show(); 
     latitude = location.Latitude; 
     longitude = location.Longitude; 
     done = true; 
    } 

    public void OnProviderDisabled(string provider){} 
    public void OnProviderEnabled(string provider){} 
    public void OnStatusChanged(string provider, [GeneratedEnum] Availability status, Bundle extras){} 
    public void Dispose() { } 
} 

調用它異步

public async Task<GeoLocation?> GetGps() 
{ 
    Toast.MakeText(Forms.Context, "Walk around to get current location", 
    ToastLength.Long).Show(); 
    var waiter = new GeolocationWaiter(); 
    locMgr.RequestLocationUpdates(Provider, 2000, 1, waiter); 
    ret = await waiter.getLocation(); 
    locMgr.RemoveUpdates(waiter); 
    return ret; 
} 

你可以在谷歌例如播放:​​3210

的源代碼:https://github.com/tripolskypetr/NearestMetro