map-with-pin

Get GPS coordinates in Windows Phone 8.1 app

If your app needs user’s device location to personalize his experience then the first step would be get its GPS coordinates. We are starting a new category of posts for handling location in windows phone 8. This one simply shows you how to get device’s GPS coordinates.

Step 1. Create a new Windows Phone 8/8.1 XAML project in Visual Studio

Choose Blank App in Store Apps> Windows Phone apps from the installed app templates, name it and create a new project.


Step 2. Add Location capability in Package.AppManifest

In the Package.AppManifest file check the Location capability under Capabilities tab.

Note: If you are developing a Windows Phone Silverlight application, you will have to add ID_CAP_LOCATION capability under Properties > WMAppManifest.xml.


Note: UnauthorizedAccessException occurs if you don’t add Location capability.

Step 3. Create a basic UI for the app

You could add just a button and a text-block to the app. The app executes the code to get the GPS coordinates when the button is clicked and displays it in the text-block.

Now you have two options. One is to get the GPS location once and use it and the other is to continuously track the location to detect any change. In this article we will discuss only single shot tracking. Step 4. Add the code behind to track GPS location

Single-shot tracking

If your app needs to track the location just once, then its best to use single shot tracking. Simply put just get the device’s GPS location and don’t use a position changed event handler with it to update the GPS coordinates whenever the device’s location changes. Here’s the click event handler code to use single shot tracking in your app.

Note:

  • We are using an async button click event so that the app could do other tasks as well and not wait for the result. It does this asynchronously so that the UI thread is not blocked while the location is obtained. You can use the await operator to place code after the asynchronous call that will be executed after the call finishes.
  • DesiredAccuracyInMeters is used to set the desired GPS accuracy level
  • The whole location operation is wrapped in a try block in case any exceptions are thrown.

That’s it. Run the app in the emulator and see it it works for you. In the emulator some random location(of mostly Microsoft in Redmond) is shown. You will get the correct coordinates when you run it on your device.

You can download the full source code of Windows Phone 8.1 XAML project here

Download full source code GPS-Location.zip

Vivek Maskara

I am pursuing BTech in Software Engineering from Delhi Technological University. I develop apps, create websites and blog about my app experiences.

Read more:
How to create your first Windows Phone app
How to change the App name and Tile name of your Windows phone app
Data binding in Windows Phone app – One way binding
Close