Get Location on Windows Phone 7

To get the geographic location of the device there ae a few steps to follow. 

1) Add a reference to System.Device

2) Add a ‘using’ line using System.Device.Location;

3) At the start of the page add a listener

GeoCoordinateWatcher watcher;

For a one time get of the location…

4) Add a button that calls the event defined here

private void StartLocationButton_Click(object sender, RoutedEventArgs e)
{
    // The watcher variable was previously declared as type GeoCoordinateWatcher.
    if (watcher == null)
    {
        watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High); // Use high accuracy.
        watcher.MovementThreshold = 20; // Use MovementThreshold to ignore noise in the signal.
        watcher.StatusChanged += new EventHandler<GeoPositionStatusChangedEventArgs>(watcher_StatusChanged);
    }
    watcher.Start();
}
5) Add the listening event that the above function calls.  It is listening for the status change.  The start above causes a status change.  Notice there is a stop at the end.  Geo Location service burns battery time.

void watcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
{
    if (e.Status == GeoPositionStatus.Ready)
    {
        // Use the Position property of the GeoCoordinateWatcher object to get the current location.
        GeoCoordinate co = watcher.Position.Location;
        latitudeTextBlock.Text = co.Latitude.ToString("0.000");
        longitudeTextBlock.Text = co.Longitude.ToString("0.000");
        //Stop the Location Service to conserve battery power.
        watcher.Stop();
    }
}

 

Happy Coding

Advertisements