系统设备位置不起作用

时间:2016-08-05 16:47:42

标签: c# windows geolocation

我有使用windows计算机中的system.device.location api的代码。这应该是相当直接的代码

var watcher = new GeoCoordinateWatcher();
        watcher.PositionChanged +=
new EventHandler<GeoPositionChangedEventArgs<
    GeoCoordinate>>(GeoPositionChanged);
        watcher.Start();
        var coord = watcher.Position.Location;

我的意思是我需要做的就是启动一个地理观察者,然后阅读该位置。但它只会返回&#34;位置未知&#34;我想知道代码是否存在问题,或者是否需要在计算机上安装某些东西,或者是什么。我尝试了几个Windows 7个窗口和1个10个窗口,所有这些都在设置中打开了共享位置。那么这段代码出了什么问题呢?如果这有任何不同,这也是geopositionchanged的代码。

    private static void GeoPositionChanged(object sender,
GeoPositionChangedEventArgs<GeoCoordinate> e)
    {
        MessageBox.Show("The current location is: " +
            e.Position.Location.Latitude + "/" +
            e.Position.Location.Longitude + ".");
    }

1 个答案:

答案 0 :(得分:2)

等待位置服务准备就绪。您的GeoCoordinateWatcher有一个状态更改事件,另一个用于更改位置。

    GeoCoordinateWatcher _watcher;
    public Class1()
    {
        _watcher = new GeoCoordinateWatcher();
        _watcher.StatusChanged += Watcher_StatusChanged;
        _watcher.PositionChanged += GeoPositionChanged;

        _watcher.Start();
        var coord = _watcher.Position.Location;
    }

    private void Watcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
    {
        if (e.Status == GeoPositionStatus.Ready)
        {
            MessageBox.Show("Watcher is ready. First location: The current location is: " +
          _watcher.Position.Location.Latitude + "/" +
          _watcher.Position.Location.Longitude + ".");
        }
    }

    private static void GeoPositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
    {
        MessageBox.Show("The current location is: " +
            e.Position.Location.Latitude + "/" +
            e.Position.Location.Longitude + ".");
    }