GeoCoordinateWatcher.TryStart 在 C# 中无法正常工作

GeoCoordinateWatcher.TryStart doesn't work properly in C#

我在使用以下代码时遇到问题,即它没有显示权限提示,因此我无法授予应用程序访问我的位置的权限,因此无法正常工作。

public Tuple<double, double> GetDeviceLocation()
{
    GeoCoordinateWatcher watcher = new GeoCoordinateWatcher();

    watcher.TryStart(false, TimeSpan.FromMilliseconds(1000));

    GeoCoordinate coord = watcher.Position.Location;

    if (coord.IsUnknown != true)
    {
        return Tuple.Create(coord.Latitude, coord.Longitude);
    }
}

我查看了 Microsoft 文档,有一些内容引起了我的注意。

The distance that must be moved, in meters, relative to the coordinate from the last PositionChanged event, before the location provider raises another PositionChanged event.

Remarks

The default movement threshold is zero, which means that any change in location detected by the current location provider causes a PositionChanged event and an update in the Position property.

   // Get location
   CLocation myLocation = new CLocation();
   myLocation.GetLocationEvent();

您必须注册 PostionChange 事件才能获取位置信息

在您需要的地方使用位置 class (CLocation)。

GeoLocation Information MSDN

    public class CLocation
   {
    GeoCoordinateWatcher watcher;

    public void GetLocationEvent()
    {
        this.watcher = new GeoCoordinateWatcher();
        this.watcher.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(watcher_PositionChanged);
        bool started = this.watcher.TryStart(false, TimeSpan.FromMilliseconds(2000));
        if (!started)
        {
            Console.WriteLine("GeoCoordinateWatcher timed out on start.");
        }
    }

    void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
    {
        PrintPosition(e.Position.Location.Latitude, e.Position.Location.Longitude);
    }

    void PrintPosition(double Latitude, double Longitude)
    {
        Console.WriteLine("Latitude: {0}, Longitude {1}", Latitude, Longitude);
    }
}