Thursday, September 8, 2011

Using Location Services on Windows Phone 7

GeoCoordinateWatcher class lives in System.Device.dll and in System.Device.Location namespace. To use it you have to add a reference in your project’s References fold and add a using reference in you .cs file if you wish.

Receive continuous location updates by subscribing to PositionChanged events:

 

1. Add a .dll reference and a using reference in you .cs file.

    using System.Device.Location;

 

2. Implement a GeoCoordinateWatcher class instance in you global scope.

    private GeoCoordinateWatcher _gcWatcher;

 

3. Subscribe to PositionChanged event and start the watcher class.

    _gcWatcher.PositionChanged += new EventHandler

          <GeoPositionChangedEventArgs<GeoCoordinate>>(_gcWatcher_PositionChanged);

    bool started = _gcWatcher.TryStart(false, TimeSpan.FromMilliseconds(2000));

    if (!started)

    {

        MessageBox.Show("Accessing GPS Faile! Unable to start your GPS device");

    }

 

4. Then, implement your event handler.

    void _gcWatcher_PositionChanged(object sender,

                                    GeoPositionChangedEventArgs<GeoCoordinate> e)

    {

        var position = e.Position.Location;

        if (position != GeoCoordinate.Unknown)

        {

            latitudeTextBlock.Text = e.Position.Location.Latitude.ToString("0.000");

            longitudeTextBlock.Text = e.Position.Location.Longitude.ToString("0.000");

        }

    }

 

5. Finally, don’t forget to stop your watcher to save the battery life.

    protected override void OnNavigatedFrom

                               (System.Windows.Navigation.NavigationEventArgs e)

    {

        if (_gcWatcher.Status != GeoPositionStatus.Disabled)

        {

            _gcWatcher.Stop();

        }

        base.OnNavigatedFrom(e);

    }

 

Create a GeoCoordinateWatcher and start acquiring data by using an initialization timeout.

1. Add a .dll reference and a using reference in you .cs file.

    using System.Device.Location;

 

2. Implement a GeoCoordinateWatcher class instance in you local scope.

    GeoCoordinateWatcher gcWatcher;

 

3. Start the watcher class.

    bool started = gcWatcher.TryStart(false, TimeSpan.FromMilliseconds(2000));

    if (!started)

    {

        MessageBox.Show("Accessing GPS Faile! Unable to start your GPS device");

    }

 

4. Then, receive your data.

    else

    {

        latitudeTBlock.Text = gcWatcher.Position.Location.Latitude.ToString("0.000");

        longitudeTBlock.Text = gcWatcher.Position.Location.Longitude.ToString("0.000");

    }

 

5. Finally, don’t forget to stop your watcher to save the battery life.

    gcWatcher.Stop();

 

Also, I have gathered two useful examples. Please go and take a look at them:

Related Topics:

No comments:

Post a Comment