Geolocation Services of Windows Phone 8


Geolocation is one of the most frequently used functionality within mobile and beyond, with it we can retrieve the location and information about our location and use an application to get other information, like restaurants, hotels, places of interest and many other scenarios. Windows Phone 8 operating the geolocation is based primarily on the following three major tools:

  • GPS
  • 3G
  • Wi-Fi

The GPS and certainly other instruments have greater precision, but with the disadvantage of requiring a high battery consumption and being outdoors for greater data accuracy.

The 3G network, based on broadband connection, uses a UMTS connection, it allows navigation on the Internet, and yes simply consume less battery than GPS, but on the contrary is much less precise.

The last, Wi-Fi, is based on connecting the router to which the device is connected, with a medium battery consumption and a good level of accuracy.

After this brief overview of the tools based on geolocation, let's see how to use it in a Windows Phone 8 application.

The Geolocator class

Windows Runtime provides for us developers the Geolocator class, that are in the Windows.Devices.Geolocation namespace. This class has several properties, methods and events, with which we can obtain all the necessary data on the position.

It has the following five properties:

  • DesiredAccuracy
  • DesiredAccuracyInMeters
  • LocationStatus
  • MovementThreshold
  • ReportInterval

The most commonly used method is:

  • GetPositionAsync ()

And finaly the two events:

  • PositionChanged
  • StatusChanged

The properties

The DesiredAccuracy property allows you to set the level of accuracy to detect the location. This property can be one of the following enumerator values: PositionAccuracy

  • Default, the receive data takes place in such a way as to ensure a normal battery consumption and updating of the position.
  • Height, if we receive data about the location more precisely, we consider, however, that by setting this value, there will be major battery consumption, whereby it should be set only if the application that we want to do requires greater data accuracy.

DesiredAccuracyInMeters, gets or sets the desired precision in meters for the data returned by the geolocation service.

LocationStatus, determines the status of the GPS signal, can be one of the following enumerator values: PositionStatus

  • Disabled, geolocation service disabled on your phone, remember that geolocation services can also be disabled by the user.
  • Initializing, geolocation service initialization phase, whereby location data may not yet be available.
  • NotAvailable, geolocation services aren't available, but since Windows Phone has GPS service always, even at low speeds, this property will never get that value.
  • NoData, geolocation services are active, but at the moment the data cannot be recovered, this happens for example when there is little or no connectivity.
  • NotInitialized, gelolocation services are active, but at the moment there has yet been no request on data recovery, has not yet been executed the method GetPositionAsync ().
  • Ready, geolocation services are active and ready for retrieval of position data.

MovementThreshold, represents the position value in meters that must be taken on the basis of the previous position.

ReportInterval, represents the minimum time in milliseconds that should elapse between a reading and the other instead.

The methods

The GetPositionAsync () method, which returns an object of type Geoposition, where we find all the information about the location, as the coordinates, that contains the latitude and longitude values, these values are primarily used, also exposes a CivicAddress properties, which in turn returns other values, as a city, country, Postal Code, province.

The events

The StatusChanged event is executed whenever the GPS signal status changes, useful then to manage the download of the location information, to warn the user in case of low or no connectivity. This event returns the connection information by using a value called Status, Position Status type, the values returned are identical to those described for the LocationStatus property.

The PositionChanged event is executed whenever it finds a new location, everything happens through the enhancement of MovementThreshold property and ReportInterval described above. The information can be found from the type Position Coordinates returned by the event. We also have the CivicAddress properties, though not being implemented, the data may not be accurate and above all accurate.

Get position with Windows Phone 8

Until now was made a brief overview of geolocation services, for a more in-depth study on the subject leave the link to the official documentation, the  MSDN Library.

Let's see how to use the services to retrieve the values of latitude and longitude. Launch Visual Studio 2013 (this example uses the Professional version), and create a new empty application project (Silverlight for Windows Phone) as shown in the figure and call it GeoPositionSample.

Confirm with the OK button, the next screen we selected a Windows Phone application 8.0.

We confirm with OK and we await the completion of the Solution. Here's how you will see the initial project.

On the left of the image is the graphic interface, whereas you insert or controls from the Toolbox, or XAML, we will show a preview of what our application will be. On the right the XAML code GUI. Since this is an empty application we have no control except for the part where they appear, "application" is "page name".

To display the latitude and longitude data, we will put in our GUI four TextBlock controls and a Button. First, let's define the XAML code four rows and two columns within the grid control named ContentPanel, where we will place all the contents of our interface.

  1. <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">  
  2.         <Grid.RowDefinitions>  
  3.             <RowDefinition Height="Auto"/>  
  4.             <RowDefinition Height="Auto"/>  
  5.             <RowDefinition Height="Auto"/>  
  6.             <RowDefinition Height="Auto"/>  
  7.         </Grid.RowDefinitions>  
  9.         <Grid.ColumnDefinitions>  
  10.             <ColumnDefinition Width="Auto"/>  
  11.             <ColumnDefinition Width="20"/>  
  12.             <ColumnDefinition Width="Auto"/>                  
  13.         </Grid.ColumnDefinitions>  
  16.         <TextBlock Grid.Row="0" Grid.Column="0" x:Name="tbkLatitude" Text="Latitude"/>  
  17.         <TextBlock Grid.Row="1" Grid.Column="0" x:Name="tbkLongitude" Text="Longitude"/>  
  18.         <TextBlock Grid.Row="0" Grid.Column="2" x:Name="tbkLatitudeValue"/>  
  19.         <TextBlock Grid.Row="1" Grid.Column="2" x:Name="tbkLongitudeValue"/>  
  21.         <Button Grid.Row="3" Grid.ColumnSpan="3" x:Name="btnFindCoordinate" Content="Find data" Tap="btnFindCoordinate_Tap"/>                          
  22.     </Grid> 

You'll notice that was created the Tap event for the Button control and where we put the necessary code to our application can interact with geolocation services. Change the value of the Text property of the TextBlock controls, that are within the StackPanel control named Titlepanel, as shown in the figure.

  1. <!--TitlePanel contiene il nome dell'applicazione e il titolo della pagina-->  
  2.      <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">  
  3.          <TextBlock Text="Geolocation Sample" Style="{StaticResource PhoneTextNormalStyle}" Margin="12,0"/>  
  4.          <TextBlock Text="Main page" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>  
  5.      </StackPanel>

After writing the code above, we will screen this aspect.

Created the necessary checks, we see this code that is needed to retrieve these values. To edit the code file, proceed with the F7 key, or in Solution Explorer expand the mainpage.xaml file until you find the MainPage.xaml.cs file. In our case, the XAML file or if we develop in VB.Net click with the mouse and be taken within the code-behind file. Earlier we said that the Windows Runtime provides the Geolocator, so the first thing to do is to add the code into the file namespace.

  1. using Windows.Devices.Geolocation; 

Let's use the Tap event and within it we write the following code.

  1. var locator = new Geolocator();  
  4.            if (!locator.LocationStatus.Equals(PositionStatus.Disabled))  
  5.            {  
  6.                var position = await locator.GetGeopositionAsync();  
  7.                tbkLatitudeValue.Text = position.Coordinate.Latitude.ToString();  
  8.                tbkLongitudeValue.Text = position.Coordinate.Longitude.ToString();  
  9.            }  
  11.            else  
  12.            {  
  13.                MessageBox.Show("Service Geolocation not enabled!", AppResources.ApplicationTitle, MessageBoxButton.OK);  
  14.                return;  
  15.            } 

How does it work? Declare a variable named type locator, it is advisable for Geolocator to check the status to verify that the services are active, otherwise we will get an exception when trying to detect the location. This run will check the value of the LocationStatus than "Disabled".

If the services are enabled, it will run the GetPositionAsync() method, which returns all the location data, it should be noted that this method is asynchronous, which means that the application will not be blocked until you download the data, but the user can continue to interact with the UI controls, provided that this article does not talk about asynchronous programming. For a greater and more detailed information on the functioning, I leave the link of the documentation MSDN.

When the GetPositionAsync() method is executed, let's enhance the TextBlock controls tbkLatitudeValue and tbkLongitudeValue with the value of the Latitude and Longitude properties of the GeoCoordinate type, then convert to a string using the ToString(), this is because it is a value of type double. The code that we have within the Tap event of the Button is defined as follows:

  1. private async void btnFindCoordinate_Tap(object sender, System.Windows.Input.GestureEventArgs e)  
  2.      {  
  3.          var locator = new Geolocator();  
  6.          if (!locator.LocationStatus.Equals(PositionStatus.Disabled))  
  7.          {  
  8.              var position = await locator.GetGeopositionAsync();  
  9.              tbkLatitudeValue.Text = position.Coordinate.Latitude.ToString();  
  10.              tbkLongitudeValue.Text = position.Coordinate.Longitude.ToString();  
  11.          }  
  13.          else  
  14.          {  
  15.              MessageBox.Show("Service Geolocation not enabled!", AppResources.ApplicationTitle, MessageBoxButton.OK);  
  16.              return;  
  17.          }  
  18.      } 

Before proceeding with the application, debugging requires enabling the capability ID_CAP_LOCATION, otherwise the application will not work. In Solution Explorer, expand the Properties folder and click on the file WMAppManifest.xml as shown in the following figure.

Open the file then go to the tab feature and select the capability.

After this activity, we can proceed with debugging the application. Importantly, if you are using the emulator, the DesiredAccuracy property must be set on High, to detect position changes. If everything is in place, our home screen will have this appearance.

Let's Tap on the Button and here we have the latitude longitude data is as expected.


In this first article we saw how to get the location by latitude and longitude. In future articles, we'll look at how to get other information that the Geolocator exposes and then exploit them in our applications and how, by latitude and longitude, have other information with the ReverseGeocodeQuery class, the methods of work are many, then we'll explore each one.

Up Next
    Ebook Download
    View all
    View all