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:
- Using Location Services on Windows Phone 7 in 31 Days of Windows Phone | Day #13: Location Services.
- GeoCoodinateWatcher Class in MSDN website.
Related Topics:
- Location Overview for Windows Phone
- Location Programming Best Practices for Windows Phone
- How to: Get Data from the Location Service for Windows Phone
- How to: Use Reactive Extensions to Emulate and Filter Location Data for Windows Phone
- How to: Test Applications that Use Location Data
- System.Device.Location Namespace
No comments:
Post a Comment