EziData Solutions

Web, NET and SQL Server

Asset Management #1 - Getting users location

While building a recent asset management app for mobile field staff, I had to create a page where they could lodge defects. Part of the lodgement process required them to select the location of the defect (latitude/longitude) and enter the physical street address.

The original HTML5 app that I built used the javascript version of Nokia HERE maps that enabled the field staff to perform these tasks, but moving to Windows Phone 8 meant that this could now be handled by the new API features.

The first step to achieve this is to add a Map control to your XAML page, remembering to include the Microsoft.Phone.Maps.Control XML namespace in the page declaration.

xmlns:maps="clr-namespace:Microsoft.Phone.Maps.Controls;assembly=Microsoft.Phone.Maps"
<maps:Map x:Name="LocationMap" />

When the user opened the page, I wanted the map to zoom to their current location to make it as quick as possible to select the asset that needed fixing. To do this, we need to initialise a Geolocator, which can be used to return the current location.

using Windows.Devices.Geolocation;

Override the OnNavigatedTo to get the current location and center the map

protected async override void OnNavigatedTo(NavigationEventArgs e)
{
    // get current location
    Geolocator locator = new Geolocator();
    Geoposition position = await locator.GetGeopositionAsync();
    var location = position.Coordinate.ToGeoCoordinate();
 
    // center the map at the current location
    LocationMap.Center = location;
    LocationMap.ZoomLevel = 18;
 
    base.OnNavigatedTo(e);
}

One catch with this process is that the classes used to represent a location from the Geolocator and the Map are similar, but actually different. The Geolocator returns a Windows.Devices.Geolocation.Geocoordinate objects, but to use this on a map we need a System.Device.Location.GeoCoordinate.

While it’s possible to write your own converter, the Windows Phone Toolkit provides a handy map extension that does the conversion for us. You’ll need to add a reference to the Toolkit in your code-behind.

using Microsoft.Phone.Maps.Toolkit;

Then you can call the ToGeoCoordinate() extension method of the Geocoordinate class.

Before testing your app, be sure to set the ID_CAP_LOCATION capability for you app in the WMAppManifest or you'll get an exception.

Posted: Jan 10 2013, 17:38 by CameronM | Comments (0) RSS comment feed |
  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Filed under: Windows Phone 8 | WP8