Click here to Skip to main content
15,881,852 members
Articles / Programming Languages / C#
Tip/Trick

Using GPS for Getting Location in Windows Phone 8

Rate me:
Please Sign up or sign in to vote.
4.36/5 (6 votes)
27 Jul 2013CPOL3 min read 40.5K   10   4
Getting location in Windows Phone 8

Introduction

I was working on a really nice Windows phone 8 application that uses geolocation techniques to pinpoint the location of your friend. This will keep track of where they go and when. Isn’t it is a great idea to trace your girlfriend’s activity, her whole routine? In my point of view, it is awesome. This post is all about sharing the basic block of such application. To get the location co-ordinates latitude and longitude via GPS.

Using the Code

To start with, let’s create a Windows Phone 8 application project:

image

Name the project and click ok. Choose your desired Windows phone OS to work with. In our case, we are choosing OS version 8.0.

image

After selecting the OS version, Visual Studio might take some time to prepare your project. Once done, you will have a mainpage.xaml presented. We might not want to do anything on the mainpage’s XAML as of now. But we do want to write some code, so navigate to the mainpage.xaml.cs file. At the very beginning, mainpage.xaml.cs will have a lot of comments than code.

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using GeolocationInWP8.Resources;
 
namespace GeolocationInWP8
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();
 
            // Sample code to localize the ApplicationBar
            //BuildLocalizedApplicationBar();
         }
 
        // Sample code for building a localized ApplicationBar
        //private void BuildLocalizedApplicationBar()
        //{
        //    // Set the page's ApplicationBar to a new instance of ApplicationBar.
        //    ApplicationBar = new ApplicationBar();
 
       // Create a new button and set the text value to the localized string from AppResources.
        //    ApplicationBarIconButton appBarButton = 
                      //new ApplicationBarIconButton
                    //(new Uri("/Assets/AppBar/appbar.add.rest.png", UriKind.Relative));
        //    appBarButton.Text = AppResources.AppBarButtonText;
        //    ApplicationBar.Buttons.Add(appBarButton);
 
        //    // Create a new menu item with the localized string from AppResources.
        //    ApplicationBarMenuItem appBarMenuItem = 
                    //new ApplicationBarMenuItem(AppResources.AppBarMenuItemText);
        //    ApplicationBar.MenuItems.Add(appBarMenuItem);
        //}
    }
} 

I suggest you remove all the commented code as it’s not doing anything, rather creating confusion. So our mainpage code will dramatically shrink to:

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using GeolocationInWP8.Resources;
 
namespace GeolocationInWP8
{
    public partial class MainPage : PhoneApplicationPage
    {
        public MainPage()
        {
            InitializeComponent();
            
        }
    }
} 

Ain’t that looking simple? Next is to initialize the GPS watcher:

C#
private void GetCoordinate()
{
   var watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High)
       {
           MovementThreshold = 1
       };
   watcher.PositionChanged += this.watcher_PositionChanged;
   watcher.Start();
}

The above function will start the watcher and will create a position changed event which will always trigger when either of the GPS coordinate (Latitude or Longitude) would change.

C#
private void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
 {
   var pos = e.Position.Location;
   LatitudeVal.Text = pos.Latitude.ToString("0.000");
   LongitudeVal.Text = pos.Longitude.ToString("0.000");
 } 

When the change in position occurs, we take the value of the Latitude and Longitude and push them all the way to the textblocks we will create in the mainpage.xaml. Let’s now move to our XAML of the mainpage. We are going to do two things here. First is to create the Loaded event of the mainpage; this invokes when the mainpage loads at the very beginning. Second is to create Textblocks to display the values onto the screen.

XML
<phone:PhoneApplicationPage
    x:Class="Getting_GPS_coordinate.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    xmlns:bm="using:Bing.Maps" 
    Loaded="MainPage_OnLoaded"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    shell:SystemTray.IsVisible="True">

    <!--LayoutRoot is the root grid where all page content is placed-->
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <!--TitlePanel contains the name of the application and page title-->
        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}" 
								Margin="12,0"/>
            <TextBlock Text="GPS Watcher" Margin="9,-7,0,0" 
				Style="{StaticResource PhoneTextTitle1Style}"/>
        </StackPanel>

        <!--ContentPanel - place additional content here-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
			<TextBlock Text="Latitude: " Width="90" Height="30" 
					HorizontalAlignment="Left" VerticalAlignment="Top"/>
			<TextBlock x:Name="LatitudeVal"  Width="90" Height="30" 
					HorizontalAlignment="Left" VerticalAlignment="Top" 
					Margin="101,0,0,0" />
			<TextBlock Text="Longitude: " Width="90" Height="30" 
					HorizontalAlignment="Left" VerticalAlignment="Top" 
					Margin="0,29,0,0"/>
			<TextBlock x:Name="LongitudeVal"  Width="90" Height="30" 
					HorizontalAlignment="Left" VerticalAlignment="Top" 
					Margin="101,28,0,0" />
        </Grid>        
    </Grid>

</phone:PhoneApplicationPage>  

As you can see, in line #10 we have created mainpage’s loaded event. And from line #34 to line #44, we have created text blocks, to hold the values. Next, we move back to code, mainpage.xaml.cs and in the mailpageloaded even that we have just created, call the GetCoordinate() method that we created before.

C#
private void MainPage_OnLoaded(object sender, RoutedEventArgs e)
{
   GetCoordinate();
}

So in the end, here is how our mainpage.xaml.cs will look like:

C#
using System;
using System.Collections.Generic;
using System.Device.Location;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Navigation;
using Microsoft.Maps.MapControl;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Getting_GPS_coordinate.Resources;
using MapLayer = Microsoft.Phone.Maps.Controls.MapLayer;

namespace Getting_GPS_coordinate
{
    public partial class MainPage : PhoneApplicationPage
    {
        GeoCoordinateWatcher watcher;
        // Constructor
        public MainPage()
        {
            InitializeComponent();
        }

        private void GetCoordinate()
        {         
            watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High)
            {
                MovementThreshold = 1
            };

            watcher.PositionChanged += this.watcher_PositionChanged;
            watcher.StatusChanged += this.watcher_StatusChanged;
            watcher.Start();
        }

        private void watcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
        {
            switch (e.Status)
            {
                case GeoPositionStatus.Disabled:
                    // location is unsupported on this device
                    break;
                case GeoPositionStatus.NoData:
                    // data unavailable
                    break;
            }
        }

        private void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
        {
            var epl = e.Position.Location;

            // Access the position information thusly:
            LatitudeVal.Text = epl.Latitude.ToString("0.000");
            LongitudeVal.Text = epl.Longitude.ToString("0.000");           
        }

        private void MainPage_OnLoaded(object sender, RoutedEventArgs e)
        {
            GetCoordinate();
        }       
    }
} 

One more step to finish our application, we need to set permission. That is, we need to request Phone that “I want to use your GPS, allow me.” In order to do that, go to solution explorer and all the way to WMAppManifest.xml in properties.

image

Navigate to capabilities tab and check ID_CAP_LOCATION.

image

That’s all we have to do. Save the project and run it.

image

Now in case you are using simulators like me to test the application, you can simulate the GPS. Just click on the “>>” in the simulator, choose location tab. Now you can simulate your position in the map, and the simulator will give you the GPS coordinates of the location you have selected.
You can download the sample project from here.

This is it for now. Stay tuned.

Happy reading!!!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India
...passionate about new things.
...love to code...
...developer by profession and programmer by nature...

Comments and Discussions

 
QuestionCoordinates always pointing to Microsoft HQ Pin
Member 1081322512-May-14 8:48
Member 1081322512-May-14 8:48 
AnswerRe: Coordinates always pointing to Microsoft HQ Pin
Mambo H29-Apr-15 16:31
professionalMambo H29-Apr-15 16:31 
QuestionThanks Pin
Hakan KOCAMAN24-Nov-13 2:50
Hakan KOCAMAN24-Nov-13 2:50 
Thank you for share.
GeneralMy vote of 4 Pin
ridoy27-Jul-13 21:45
professionalridoy27-Jul-13 21:45 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.