Over a million developers have joined DZone.

Simulating GPS position changes using Reactive Extensions in Windows Phone environment

· Mobile Zone
It has become much easier to simulate GPS position change events having Location tool in Emulator, where you are able to pin positions on a map, but for some Unit Tests and mock services it is important to simulate GPS data programmatically. For this reason you would obviously use Reactive Extensions(Rx). Rx allows you to create Observable interface implementation based on Timer and attach it to position reading method. Bellow is the code I use to generate a GeoPosition with random Latitude and Longitude parameters. If isSimulation variable is set to true then simulation mode is activated, otherwise application uses standard GPS functionality.


private readonly GeoCoordinateWatcher _gcw = new GeoCoordinateWatcher();
 
private readonly Random _random = new Random();
 
public GpsSamplePage()
{
    InitializeComponent();
 
    bool isSimulation = true;
    if (!isSimulation)
    {
        _gcw.PositionChanged += (s, e) => GcwPositionChanged(e);
        _gcw.Start();
    }
    else
    {
        Observable.Timer(TimeSpan.FromSeconds(0), TimeSpan.FromSeconds(4))
        .Select(x =>
            new GeoPositionChangedEventArgs<GeoCoordinate>(
                new GeoPosition<GeoCoordinate>(DateTime.Now,
                    new GeoCoordinate()
                        {
                            // -90 <= latitude <= 90
                            Latitude = (_random.NextDouble() * 180.0) - 90.0,
                            // -180 <= longitude <= 180
                            Longitude = (_random.NextDouble() * 360.0) - 180.0
                        }
 
                ))).ObserveOnDispatcher().Subscribe(GcwPositionChanged);
    }
}
 
void GcwPositionChanged(GeoPositionChangedEventArgs<GeoCoordinate> e)
{
    Dispatcher.BeginInvoke(() =>
    {
        // thread safe
        tbLatitude.Text = e.Position.Location.Latitude.ToString();
        tbLongitude.Text = e.Position.Location.Longitude.ToString();
    });
}

Source: http://www.eugenedotnet.com/2011/11/simulating-gps-position-changes-using-reactive-extensions-in-windows-phone-environment/
Topics:

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}