MobileUsing the Location API in Your Windows Phone 8 Applications

Using the Location API in Your Windows Phone 8 Applications

Introduction

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.

There are two location APIs. One is the .NET location API, which resides in the namespace System.Device.Location and is implemented in the GeoCoordinateWatcher class. You need to create an object of this class to start the acquisition of data from the Location Service. You would use this API if you were migrating a Windows Phone 7 application to Windows Phone 8, with minimalist changes.

If you were starting fresh, you are better off using the Windows Phone Runtime API for creating location-aware apps. The Windows Phone Runtime API is new in Windows Phone 8 and did not exist in Windows Phone 7.x versions.

These runtime location APIs are accessible from both managed and native code. Additionally, they support better accuracy of the location and well as permissible latency to derive results.

To get access to location, a Windows Phone application will need to declare the LOCATION capability, which exists in WMAppManifest.xml file as ID_CAP_LOCATION. The location APIs are implemented by the Geolocator class in the Windows.Devices.Geolocation namespace.

The location APIs also support notifying changes in position, which can be used if one is building a GPS application. The change in position is notified by the Geolocator.PositionChanged event. When the GPS state changes, the Geolocator.StatusChanged event is fired.

Hands-On

In our demo, we will build a simple Windows Phone application, which will enable the Geolocator and retrieve the latitude and longitude of the current location. Additionally, we will have controls that will help us capture when the status of the Geolocator object changes.

Start Visual Studio 2012 and create a new Windows Phone 8 application titled WindowsPhoneLocationDemo.

New Project
New Project

When prompted, select Windows Phone OS  8.0 as the target Windows Phone OS version.

New Windows Phone Application
New Windows Phone Application

Next, open the WMAppManifest.xml and declare the location capability by selecting ID_CAP_LOCATION.

WMAppManifest.xml
WMAppManifest.xml

Next, on MainPage.xaml, add controls so that your MainPage.xaml looks like the screenshot below.

MainPage.xaml
MainPage.xaml

To do this, you will need three textblocks (one named Latitude, one named Longitude and one named “GPS status”), three textboxes (which will contain the values for latitude, longitude and the current GPS status), and two buttons – one to enable the GPS and the other to disable GPS (scope of this button is to only stop processing GPS status changes and position changes).

Next, we will declare the Geolocation namespace in the “using” section of MainPage.xaml.cs.

using
Windows.Devices.Geolocation;

Next, we will declare an object of type Geolocator called myGeoLocator.

public partial class MainPage : PhoneApplicationPage
    {
        Geolocator myGeoLocator;
        
        // Constructor
        public MainPage()

Now, we will wire up the event handler for the Click event on the “Enable GPS button”. In the event handler, we will initialize a new instance of Geolocator and also wire up the event handlers for the StatusChanged and Positionchanged events of the Geolocator object. Finally, we will disable the “Enable GPS” button and enable the “Disable GPS” button.

private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            myGeoLocator = new Geolocator();
            myGeoLocator.DesiredAccuracy = PositionAccuracy.Default;
            myGeoLocator.MovementThreshold = 50;
            myGeoLocator.StatusChanged += myGeoLocator_StatusChanged;
            myGeoLocator.PositionChanged += myGeoLocator_PositionChanged;
            
            
            
            buttonEnableGPS.IsEnabled = false;
            buttonDisableGPS.IsEnabled = true;
 
 
        }

Now, we will   wire up the Click event for the “Disable GPS” button, where we will essentially reverse what we did in the click event for “Enable GPS” button.

private void buttonDisableGPS_Click(object sender, RoutedEventArgs e)
        {
            myGeoLocator.PositionChanged -= myGeoLocator_PositionChanged;
            myGeoLocator.StatusChanged -= myGeoLocator_StatusChanged;
            
            myGeoLocator = null;
            buttonEnableGPS.IsEnabled = true;
            buttonDisableGPS.IsEnabled = false;
        }

Finally, we will write the code for the PositionChanged event handler. In this event handler, we will process the StatusChangedEventArgs, process the positionstatus and display it in the textbox for GPS status.

void myGeoLocator_StatusChanged(Geolocator sender, StatusChangedEventArgs args)
        {
            PositionStatus ps = args.Status;
            Dispatcher.BeginInvoke(() =>
            {
                textBoxGPSStatus.Text = ps.ToString();
            });
        }

We will also process the PositionChanged event. In this event, we will look at the position information we get from the geolocation object and display it in the textboxes for latitude and longitude.

void myGeoLocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args)
        {
            Dispatcher.BeginInvoke(() =>
            {
                textBlockLocationLatitute.Text = args.Position.Coordinate.Latitude.ToString("0.00");
                textBlockLocationLongitute.Text = args.Position.Coordinate.Longitude.ToString("0.00");
            });
        }
 

Now, your application is complete. If you have trouble following along, you can download sample code from here.

Once you deploy your application, your application will look like the screenshot below.

Your application
Your application

When we click the Enable GPS button, your app will look like the screenshot below.

Click the Enable GPS button
Click the Enable GPS button

We can see that the application returns the current location and also the GPS status, which in my case is Ready.

Summary

In this article, we saw how to use the location APIs to build location-aware applications. I hope you have found this article useful.

About the author

Vipul Patel is a Program Manager currently working at Amazon Corporation. He has formerly worked at Microsoft in the Lync team and in the .NET team (in the Base Class libraries and the Debugging and Profiling team). He can be reached at vipul.patel@hotmail.com

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories