trinityalps
trinityalps

Reputation: 397

System Device Location not working

I have code for using the system.device.location api found in windows computers. This should be fairly straightfoward code

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

I mean all I need to do is start a geo watcher and then read the location. But it only ever returns "Location Unknown" and I am wondering if there is an issue with the code, or if something needs to be installed on the computer, or what. I have tried this with a few windows 7 pcs and 1 windows 10 pc and all of them have the share location turned on in the settings. So what is wrong with this code? Also this is the code for the geopositionchanged if that makes any difference.

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

Upvotes: 1

Views: 6462

Answers (1)

Odrai
Odrai

Reputation: 2353

Wait for location services to be ready. Your GeoCoordinateWatcher has an event for status change and another one for position change.

    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 + ".");
    }

Upvotes: 2

Related Questions