Windows Phone 8 provides application developers with the ability to build applications, which can utilize the new location APIs in the platform.
Windows Phone 8 platform allows the device to derive the location information from various sources like GPS, Wi-Fi and cellular triangulation.
In the new WP8 SDK, a new set of run-time APIs are added to get the current location of the phone. One can also use background location tracking in their apps which continues tracking location in the background even if the user has closed the app.
Location API is actually a cool feature and can be used in many ways in you app like help your friends to find you or vice versa, integrate with Maps and navigate and what not.. The app on which I am working on involves this feature and it is actually very very easy to implement. All you have to do is to go through the steps below and tada ! you will get the current location of your phone!
How to go about it?
Before using the location API in your app make sure you enable the location capability in the WMAppManifest.xml by just the checking the box with the element ID_CAP_LOCATION inside the capabilities tab.
You can also do the same by adding the element ID_CAP_LOCATION in the WMAppManifest.xmlfile.
The Next step is to modify the UI for getting the location and displaying it. You can either use Blend for designing UI and adding assets like button, Textblocks etc to serve the purpose or you can directly write in the MainPage.xaml code. In order to get the current location, you need two textblocks (one for displaying the latitude and second to display longitude) and a button which on click gives the current location.
New API for getting the current location:
The new location APIs are exposed through the Geolocator class. In order to get the phone’s current location we simply call the GetGeopositionAsync method and we can also set the desired accuracy and movement threshold and we format the coordinates using the GetCoordinateString method and display the result in the text block.
Include the following namespace in MainPage.xaml.cs :
private async void Button1_Click(object sender, RoutedEventArgs e)
Geolocator geolocator = new Geolocator();
geolocator.DesiredAccuracyInMeters = 50;
Geoposition geoposition = await geolocator.GetGeopositionAsync(
LatitudeTextBlock.Text = geoposition.Coordinate.Latitude.ToString("0.00");
LongitudeTextBlock.Text = geoposition.Coordinate.Longitude.ToString ("0.00");
// the app does not have the right capability or the location master switch is off
StatusTextBlock.Text = "location is disabled in phone settings.";
I hope you find this article useful while developing your apps involving this new Location API in WP8.