首页 文章

Xamarin表格获取位置

提问于
浏览
1

我正在尝试执行下面的代码

var locator = CrossGeolocator.Current;

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

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

在Xamarin Forms中使用Xam.plugin.Geolocator但获得 "This functionality is not implemented in the portable version of this assembly. You should reference the NuGet package from your main application project in order to reference the platform-specific implementation." 异常 .

我从这个链接使用3.0.4版本的Xam.plugin.Geolocator https://www.nuget.org/packages/Xam.Plugin.Geolocator

我在Potable项目和droid项目中添加了nuget包 . 添加

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

在AssemblyInfo.cs中 . 还确保在Visual Studio 2015中的Android Manifest中选中“Access_Coarse_Location”和“Access_Fine_Locations” .

任何人都可以帮助我失踪吗?

1 回答

  • 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;
    }
    

    您可以在Google Play上获取示例:https://play.google.com/store/apps/details?id=com.simplesoft.metro

    源代码:https://github.com/tripolskypetr/NearestMetro

相关问题