Using GPS For Getting Location in Windows Phone 8

I was working on a really nice Windows Phone 8 application that uses geolocation techniques to pinpoint a current location. This will track where someone goes and when. In my point of view, ths is awesome. This article is all about sharing the basics of such application. To get the latitude and longitude location co-ordinates via GPS.

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

GPS-for-Getting-Location-in-Windows-Phone 8.jpg

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.

GPS-for-Getting-Location-in-Windows-Phone 81.jpg

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 more comments than code.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Windows;  
  6. using System.Windows.Controls;  
  7. using System.Windows.Navigation;  
  8. using Microsoft.Phone.Controls;  
  9. using Microsoft.Phone.Shell;  
  10. using GeolocationInWP8.Resources;  
  11. namespace GeolocationInWP8  
  12. {  
  13.     public partial class MainPage : PhoneApplicationPage  
  14.     {  
  15.         // Constructor  
  16.         public MainPage()  
  17.         {  
  18.             InitializeComponent();  
  19.             // Sample code to localize the ApplicationBar  
  20.             // BuildLocalizedApplicationBar();  
  21.         }  
  22.         // Sample code for building a localized ApplicationBar  
  23.         //private void BuildLocalizedApplicationBar()  
  24.         //{  
  25.         // // Set the page's ApplicationBar to a new instance of ApplicationBar.  
  26.         // ApplicationBar = new ApplicationBar();   
  27.         // // Create a new button and set the text value to the localized string from AppResources.  
  28.         // ApplicationBarIconButton appBarButton =  
  29.         //new ApplicationBarIconButton  
  30.         //(new Uri("/Assets/AppBar/appbar.add.rest.png", UriKind.Relative));  
  31.         // appBarButton.Text = AppResources.AppBarButtonText;  
  32.         // ApplicationBar.Buttons.Add(appBarButton);   
  33.         // // Create a new menu item with the localized string from AppResources.  
  34.         // ApplicationBarMenuItem appBarMenuItem =  
  35.         //new ApplicationBarMenuItem(AppResources.AppBarMenuItemText);  
  36.         // ApplicationBar.MenuItems.Add(appBarMenuItem);  
  37.         //}  
  38.     }  
  39. }  

I suggest you to remove all the commented code since it's not doing anything more than creating confusion. So our mainpage code will dramatically shrink to:

  1.  using System;  
  2.  using System.Collections.Generic;  
  3.  using System.Linq;  
  4.  using System.Net;  
  5.  using System.Windows;  
  6.  using System.Windows.Controls;  
  7.  using System.Windows.Navigation;  
  8.  using Microsoft.Phone.Controls;  
  9.  using Microsoft.Phone.Shell;  
  10.  using GeolocationInWP8.Resources;  
  11.  namespace GeolocationInWP8  
  12.  {  
  13.        public partial class MainPage : PhoneApplicationPage  
  14.       {  
  15.           public MainPage()  
  16.           {  
  17.               InitializeComponent();  
  18.           }  
  19.        }  
  20.  }  
  21.    
  22. Ain't that looking simple? Next is to initialize the GPS watcher:  
  23.    
  24. private void GetCoordinate()  
  25. {  
  26.     var watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High)  
  27.     {  
  28.        MovementThreshold = 1  
  29.     }; 
  30.  
  31.     watcher.PositionChanged += this.watcher_PositionChanged;  
  32.     watcher.Start();  
  33. }  
  34. The function above will start the watcher and will create a position changed event that will always trigger when either of the GPS coordinates (Latitude or Longitude) change.  
  35.   
  36. private void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)  
  37. {  
  38.     var pos = e.Position.Location;  
  39.     LatitudeVal.Text = pos.Latitude.ToString("0.000");  
  40.     LongitudeVal.Text = pos.Longitude.ToString("0.000");  
  41. }  

When the change in position occures, 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 will do two things here. The first is to create the Loaded event of the mainpage; this is invoked when the mainpage loads at the very beginning. The second is to create Textblocks to display the values onto the screen.

  1. <phone:PhoneApplicationPage  
  2. x:Class="GeolocationInWP8.MainPage"  
  3. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
  4. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
  5. xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"  
  6. xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"  
  7. xmlns:d="http://schemas.microsoft.com/expression/blend/2008"  
  8. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"  
  9. mc:Ignorable="d"  
  10. Loaded="MainPage_OnLoaded"  
  11. FontFamily="{StaticResource PhoneFontFamilyNormal}"  
  12. FontSize="{StaticResource PhoneFontSizeNormal}"  
  13. Foreground="{StaticResource PhoneForegroundBrush}"  
  14. SupportedOrientations="Portrait" Orientation="Portrait"  
  15. shell:SystemTray.IsVisible="True">  
  16.   <!--LayoutRoot is the root grid where all page content is placed-->  
  17.   <Grid x:Name="LayoutRoot" Background="Transparent">  
  18.     <Grid.RowDefinitions>  
  19.       <RowDefinition Height="Auto"/>  
  20.       <RowDefinition Height="*"/>  
  21.     </Grid.RowDefinitions>  
  22.     <!--TitlePanel contains the name of the application and page title-->  
  23.     <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">  
  24.       <TextBlock Text="MY APPLICATION"  
  25.       Style="{StaticResource PhoneTextNormalStyle}" Margin="12,0"/>  
  26.       <TextBlock Text="GPS" Margin="9,-7,0,0"  
  27.        Style="{StaticResource PhoneTextTitle1Style}"/>  
  28.     </StackPanel>  
  29.     <!--ContentPanel - place additional content here-->  
  30.     <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">  
  31.       <TextBlock Text="Latitude: " Width="90" Height="30"  
  32.       HorizontalAlignment="Left" VerticalAlignment="Top"/>  
  33.       <TextBlock x:Name="LatitudeVal" Width="90" Height="30"  
  34.       HorizontalAlignment="Left" VerticalAlignment="Top"  
  35.       Margin="101,0,0,0" />  
  36.       <TextBlock Text="Longitude: " Width="90" Height="30"  
  37.       HorizontalAlignment="Left" VerticalAlignment="Top"  
  38.       Margin="0,29,0,0"/>  
  39.       <TextBlock x:Name="LongitudeVal" Width="90" Height="30"  
  40.       HorizontalAlignment="Left" VerticalAlignment="Top"  
  41.       Margin="101,28,0,0" />  
  42.     </Grid>  
  43.   </Grid>  
  44. </phone:PhoneApplicationPage>  

As you can see, in line #10 we have created a 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 just have created call the GetCoordinate() method that we created before.

  1. private void MainPage_OnLoaded(object sender, RoutedEventArgs e)  
  2. {  
  3.    GetCoordinate();  
  4. }  

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

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Device.Location;  
  4. using System.Linq;  
  5. using System.Net;  
  6. using System.Windows;  
  7. using System.Windows.Controls;  
  8. using System.Windows.Navigation;  
  9. using Microsoft.Phone.Controls;  
  10. using Microsoft.Phone.Shell;  
  11. using GeolocationInWP8.Resources;  
  12. namespace GeolocationInWP8  
  13. {  
  14.     public partial class MainPage : PhoneApplicationPage  
  15.     {  
  16.         public MainPage()  
  17.         {  
  18.             InitializeComponent();  
  19.         }  
  20.         private void GetCoordinate()  
  21.         {  
  22.             var watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High)  
  23.             {  
  24.                 MovementThreshold = 1  
  25.             };  
  26.             watcher.PositionChanged += this.watcher_PositionChanged;  
  27.             watcher.Start();  
  28.         }  
  29.         private void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)  
  30.         {  
  31.             var pos = e.Position.Location;  
  32.             LatitudeVal.Text = pos.Latitude.ToString("0.000");  
  33.             LongitudeVal.Text = pos.Longitude.ToString("0.000");  
  34.         }  
  35.         private void MainPage_OnLoaded(object sender, RoutedEventArgs e)  
  36.         {  
  37.             GetCoordinate();  
  38.         }  
  39.     }  
  40. }  

One more step to finish our application is that we need to set permission. That is, we need to request the 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.

GPS-for-Getting-Location-in-Windows-Phone2.jpg

Navigate to the capabilities tab and check ID_CAP_LOCATION.

GPS-for-Getting-Location-in-Windows-Phone3.jpg

That's all we must do. Save the project and run it.

GPS-for-Getting-Location-in-Windows-Phone4.jpg

Now in case you are using emulators like me, to test the application,. You can simulate the GPS. Just click on the ">>" in the emulator then choose the 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 above or from http://www.4shared.com/rar/619W7qBz/GeolocationInWP8.html


Similar Articles