CrossGeolocator的GetPositionAsync不起作用

时间:2017-01-20 12:18:49

标签: c# mobile xamarin

我正在使用 CrossGeolocator 来检索设备的当前纬度和经度。但是我在 OnAppearing 覆盖方法中使用它并且它无法正常工作。 GetPositionAsync 方法会挂起App。

 protected override void OnAppearing()
 {
     base.OnAppearing();

     var position = GetPosition().Result;
     var lat = position.Latitude;
     var lon = position.Longitude;
 }

 private static async Task<Position> GetPosition()
 {
     var locator = CrossGeolocator.Current;
     locator.DesiredAccuracy = 50;

     var position = await locator.GetPositionAsync(10000);
     return position;
 }

详细说明我在应用程序的按钮中使用了相同的 GetPosition 方法,效果很好。

有人可以帮我解决这个问题吗?

5 个答案:

答案 0 :(得分:4)

试试这个:

创建一个全局变量:

private Position _position;

然后调用ur方法获取构造函数的位置。 像这样重写你的方法:

public async void GetPosition()
{
    var locator = CrossGeolocator.Current;
    locator.DesiredAccuracy = 50;
    var myPosition = await locator.GetPositionAsync();
    _position = new Position(myPosition.Latitude, myPosition.Longitude);
}

然后在你想要使用它的地方做一段时间:

while(_position == new Postion(0,0))
      GetPosition();

答案 1 :(得分:2)

这对我有用。

设置链接中所述的xamarin表单映射。 https://developer.xamarin.com/guides/xamarin-forms/user-interface/map/

设置权限,如下面的链接所示 https://jamesmontemagno.github.io/GeolocatorPlugin/GettingStarted.html

您可以使用https://jamesmontemagno.github.io/GeolocatorPlugin/CurrentLocation.html

using Plugin.Geolocator;
using System;
using Xamarin.Forms;
using Xamarin.Forms.Maps;
using Xamarin.Forms.Xaml;
namespace MapApp
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class MapPage : ContentPage
    {
        private Position _position;
        public MapPage()
        {
            InitializeComponent();

            var map = new Map(
              MapSpan.FromCenterAndRadius(
                      new Position(37, -122), Distance.FromMiles(0.3)))
            {
                IsShowingUser = true,
                HeightRequest = 100,
                WidthRequest = 960,
                VerticalOptions = LayoutOptions.FillAndExpand
            };



            if (IsLocationAvailable())
            {
                GetPosition();
                map.MoveToRegion(MapSpan.FromCenterAndRadius(_position, Distance.FromMiles(1)));

            }

            map.MapType = MapType.Street;
            var stack = new StackLayout { Spacing = 0 };
            stack.Children.Add(map);
            Content = stack;

        }

        public bool IsLocationAvailable()
        {
            if (!CrossGeolocator.IsSupported)
                return false;

            return CrossGeolocator.Current.IsGeolocationAvailable;
        }
        public async void GetPosition()
        {
            Plugin.Geolocator.Abstractions.Position position = null;
            try
            {
                var locator = CrossGeolocator.Current;
                locator.DesiredAccuracy = 100;

                position = await locator.GetLastKnownLocationAsync();

                if (position != null)
                {
                    _position = new Position(position.Latitude, position.Longitude);
                    //got a cahched position, so let's use it.
                    return;
                }

                if (!locator.IsGeolocationAvailable || !locator.IsGeolocationEnabled)
                {
                    //not available or enabled
                    return;
                }

                position = await locator.GetPositionAsync(TimeSpan.FromSeconds(20), null, true);

            }
            catch (Exception ex)
            {
                throw ex;
                //Display error as we have timed out or can't get location.
            }
            _position = new Position(position.Latitude, position.Longitude);
            if (position == null)
                return;

        }

    }
}

答案 2 :(得分:1)

要注意的事情是

在构造函数中调用方法。 如果存在,则可以使用lat long。 非常IMP尝试捕获,而不尝试捕获应用程序崩溃。不要把任何东西写成不要写;不想抓住异常。

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Foundation;
using UIKit;
using System.Threading.Tasks;
using Plugin.Geolocator.Abstractions;
using Plugin.Geolocator;
using System.Diagnostics;
using Xamarin.Forms;
using abcde.iOS;

[assembly: Xamarin.Forms.Dependency(typeof(GPSLocation_iOS))]

namespace abcde.iOS
{
public class GPSLocation_iOS : IGPSLocation
{
public Position _position;

    public GPSLocation_iOS()
    {
        GetPosition();
    }

    public Dictionary<string, string> GetGPSLocation()
    {
    Dictionary<string, string> dictPosition = new Dictionary<string, string>();

    dictPosition.Add("latitude", _position.Latitude.ToString());
    dictPosition.Add("longitude", _position.Longitude.ToString());

      return dictPosition;
    }

    public async void GetPosition()
    {
        try
        {
            var locator = CrossGeolocator.Current;

            _position = await locator.GetLastKnownLocationAsync();

            if (_position == null)
            {
      locator.DesiredAccuracy = 50;
      var myPosition = await locator.GetPositionAsync();
      _position = new Position(myPosition.Latitude, myPosition.Longitude);
            }
        }
        catch (Exception ex)
        {

        }
    }

答案 3 :(得分:0)

最新的2018-07-10版本更新

要支持iOS 11及更低版本,您可以包括所有三个键:

  • NSLocationWhenInUseUsesDescription,
  • NSLocationAlwaysAndWhenInUseUsageDescription
  • NSLocationAlwaysUsageDescription。

我使用Xamarin编写应用程序,并且在我的iOS项目中工作正常

引用:https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/map

答案 4 :(得分:0)

我仅在GetPositionAsync中添加参数即可解决我的问题:null和true。

var location = await locator.GetPositionAsync(TimeSpan.FromSeconds(20),null,true);

并打开GPS

我的问题是在Android 4.4上