Saturday, August 7, 2010

Getting Started with Windows Phone 7 GPS and Location Services

It’s super simple and straight-forward to get started with using Location Services on Windows Phone 7.

The following source code is a quick snippet that shows you the key components for working with the GPS.

private void GpsTracking_Click(object sender, EventArgs e)
{
    if (watcher != null)
    {
        watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High);
        watcher.MovementThreshold = 20;

        watcher.StatusChanged += watcher_StatusChanged;
        watcher.PositionChanged += watcher_PositionChanged;
        watcher.Start();
    }
    else
    {
        if (watcher.Status == GeoPositionStatus.Disabled)
            watcher.Start();
        else
            watcher.Stop();
    }
}

void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
{
    Dispatcher.BeginInvoke(() =>
        Map.CenterOnLocation(
                        new Coord(e.Position.Location.Longitude, e.Position.Location.Latitude),
                        e.Position.Location.Course,  e.Position.Location.Speed, 
                        e.Position.Location.HorizontalAccuracy, e.Position.Location.VerticalAccuracy)
    );
}

void watcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
{
    Dispatcher.BeginInvoke(() =>
        Map.UpdateGPSStatus(e.Status.ToString())
    );
}

The MSDN documentation is available here.

So now you are asking yourself, well Kevin, yes that is all very nice, but I don’t have a device, how the heck am I supposed to test this?  Simple – use this very cool little utility provided by Ali Tinwala

Enjoy!

-twb

No comments:

Post a Comment