如何使用xamrian表单提示用户进行地理定位

您好我正在使用xamrian表单应用程序中的应用程序,需要请求gelocation权限,如果授权它需要从设备获取地理位置数据,然后将地理位置坐标放入forecast.io URL我正在使用Geolocator插件詹姆斯·蒙特马尼奥以及詹姆斯·蒙特马尼奥的PermissionsPlugin,当我打开雷达页面时,屏幕保持白色,它永远不会要求我的许可,这是我的xamrain表单代码:

using AppName.Data; using Xamarin.Forms; using Plugin.Geolocator; using System.Diagnostics; using System.Threading.Tasks; using Plugin.Permissions; using Plugin.Permissions.Abstractions; using System; namespace AppName.Radar { public partial class RadarHome : ContentPage { public RadarHome() { InitializeComponent(); } async void locator() { try { var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Location); if (status != PermissionStatus.Granted) { if (await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(Permission.Location)) { await DisplayAlert("Need location", "Gunna need that location", "OK"); } var results = await CrossPermissions.Current.RequestPermissionsAsync(Permission.Location); status = results[Permission.Location]; } if (status == PermissionStatus.Granted) { var browser = new WebView(); var results = await CrossGeolocator.Current.GetPositionAsync(10000); browser.Source = "https://forecast.io/?mobile=1#/f/" + "Lat: " + results.Latitude + " Long: " + results.Longitude; } else if (status != PermissionStatus.Unknown) { await DisplayAlert("Location Denied", "Can not continue, try again.", "OK"); } } catch (Exception ex) { await DisplayAlert("Location Denied", "Can not continue, try again.", "OK"); } } } } 

并且我的Android MainActivity代码:

 using Android.App; using Android.Content.PM; using Android.OS; using Xamarin.Forms.Platform.Android; using Android; using Plugin.Permissions; namespace AppName.Droid { [Activity(MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation, Theme = "@style/CustomTheme")] public class MainActivity : FormsApplicationActivity { protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); global::Xamarin.Forms.Forms.Init(this, bundle); LoadApplication(new App()); } public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Permission[] grantResults) { PermissionsImplementation.Current.OnRequestPermissionsResult(requestCode, permissions, grantResults); } } } 

我要留下什么了? 这两个插件都安装在android项目和iOS项目的表单项目中

提前致谢!

您需要添加所需的权限。

Android中 ,要允许我们的应用程序访问位置服务,我们需要启用两个Android权限: ACCESS_COARSE_LOCATIONACCESS_FINE_LOCATION

iOS中 ,根据您是否始终使用地理位置(例如地图应用程序),或仅在用户工作流程中的某些点,您需要在Info.plist添加密钥NSLocationWhenInUsageDescriptionNSLocationAlwaysUsageDescription ,以及密钥的新字符串条目,用于准确描述您将对用户的位置执行的操作。 在运行时向用户提示权限时,将显示此处列出的说明。

在Windows中,必须启用ID_CAP_LOCATION权限。

阅读有关它的完整博客 – 适用于iOS,Android和Windows Made Easy的地理定位

1. Xamarin接口

  public interface MyLocationTracker { void ObtainMyLocation(); event EventHandler locationObtained; } public interface MyLocationEventArgs { double lat { get; set; } double lng { get; set; } } 

2. Android依赖代码

 [assembly: Xamarin.Forms.Dependency(typeof(GetMyLocationStatus))] namespace BarberApp.Droid { public class GetMyLocationStatus: Java.Lang.Object,MyLocationTracker,ILocationListener { private LocationManager _locationManager; private string _locationProvider; private Location _currentLocation { get; set; } public GetMyLocationStatus() { this.InitializeLocationManager(); } public event EventHandler locationObtained; event EventHandler MyLocationTracker.locationObtained { add { locationObtained += value; } remove { locationObtained -= value; } } void InitializeLocationManager() { _locationManager = (LocationManager)Forms.Context.GetSystemService(Context.LocationService); } public void OnLocationChanged(Location location) { _currentLocation = location; if (location != null) { LocationEventArgs args = new LocationEventArgs(); args.lat = location.Latitude; args.lng = location.Longitude; locationObtained(this, args); } } void MyLocationTracker.ObtainMyLocation() { _locationManager = (LocationManager)Forms.Context.GetSystemService(Context.LocationService); if (!_locationManager.IsProviderEnabled(LocationManager.GpsProvider) || !_locationManager.IsProviderEnabled(LocationManager.NetworkProvider)) { AlertDialog.Builder builder = new AlertDialog.Builder(Forms.Context); builder.SetTitle("Location service not active"); builder.SetMessage("Please Enable Location Service and GPS"); builder.SetPositiveButton("Activate", (object sender, DialogClickEventArgs e) => { Intent intent = new Intent(Android.Provider.Settings.ActionLocationSourceSettings); Forms.Context.StartActivity(intent); }); Dialog alertDailog = builder.Create(); alertDailog.SetCanceledOnTouchOutside(false); alertDailog.Show(); } else { _locationManager.RequestLocationUpdates( LocationManager.NetworkProvider, 0, //---time in ms--- 0, //---distance in metres--- this); } } ~GetMyLocationStatus(){ _locationManager.RemoveUpdates(this); } } public class LocationEventArgs : EventArgs, MyLocationEventArgs { public double lat { get; set; } public double lng { get; set; } } } 

3. IOS依赖代码

 [assembly: Xamarin.Forms.Dependency(typeof(GetILocationStatus))] namespace BarberApp.iOS { public class GetILocationStatus : MyLocationTracker { public GetILocationStatus() { } CLLocationManager lm; public event EventHandler locationObtained; event EventHandler MyLocationTracker.locationObtained { add { locationObtained += value; } remove { locationObtained -= value; } } void MyLocationTracker.ObtainMyLocation() { lm = new CLLocationManager(); lm.DesiredAccuracy = CLLocation.AccuracyBest; lm.DistanceFilter = CLLocationDistance.FilterNone; lm.LocationsUpdated += (object sender, CLLocationsUpdatedEventArgs e) => { var locations = e.Locations; var strLocation = locations[locations.Length - 1]. Coordinate.Latitude.ToString(); strLocation = strLocation + "," + locations[locations.Length - 1]. Coordinate.Longitude.ToString(); LocationEventArgs args = new LocationEventArgs(); args.lat = locations[locations.Length - 1]. Coordinate.Latitude; args.lng = locations[locations.Length - 1]. Coordinate.Longitude; locationObtained(this, args); }; lm.AuthorizationChanged += (object sender, CLAuthorizationChangedEventArgs e) => { if (e.Status == CLAuthorizationStatus.AuthorizedWhenInUse) { lm.StartUpdatingLocation(); } }; lm.RequestWhenInUseAuthorization(); } ~GetILocationStatus() { lm.StopUpdatingLocation(); } } public class LocationEventArgs : EventArgs, MyLocationEventArgs { public double lat { get; set; } public double lng { get; set; } } } 

4. Xamarin表格代码

 MyLocationTracker msi; double BetaLat; double BetaLog; var locator = CrossGeolocator.Current; if (locator.IsGeolocationEnabled == false) { if (Device.OS == TargetPlatform.Android) { msi = DependencyService.Get(); msi.locationObtained += (object Esender, MyLocationEventArgs ew) => { Console.WriteLine(ew.lat); }; msi.ObtainMyLocation(); } else if (Device.OS == TargetPlatform.iOS) { msi = DependencyService.Get(); msi.locationObtained += (object Jsender, MyLocationEventArgs je) => { Console.WriteLine(je.lat); }; msi.ObtainMyLocation(); } } locator.DesiredAccuracy = 50; var position = locator.GetPositionAsync(timeoutMilliseconds: 100000); BetaLat = position.Latitude; BetaLog = position.Longitude; string str = string.Format("https://forecast.io/?mobile=1#/f/Lat:{0} , Long: {1}", BetaLat, BetaLog); var client = new System.Net.Http.HttpClient(); client.BaseAddress = new Uri(str); 

我有同样的问题,这个插件在运行时没有请求权限,即使它显示在Droid属性页面上。 解决方法是手动将此行复制并粘贴到manifest.xml文件中。

  

出于某种原因,Xamarin在属性页面中进行设置时未更新此行以包含targetSdkVersion。

希望这可以帮助别人,因为我花了几个小时试图解决这个问题!

由JamesMontemagno创建的Xam.Plugin.Geolocator插件有一个很好的例子来说明如何做到这一点。

以下是如何获得使用GPS的权限 – 权限实现示例

以下是如何实现它的示例(包括检查GPS是否已打开) – GPS实施示例

阅读Readme.md以获取所需的更多系统特定操作