Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Geolocation services on Windows Phone 8.

0.00/5 (No votes)
22 Aug 2014 2  
Geolocation is one of the most frequently used functionality within mobile and beyond, with it we can retrieve the location and information about the place where.

Introduction

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

  • GPS
  • 3G
  • Wi-Fi

The Gps and certainly the instrument with 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 UMTS connection, it allows navigation on Internet, has Yes simply consume less battery than Gps, but on the contrary and 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 that it is 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, which 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.

Has five properties:

  • DesiredAccuracy
  • DesiredAccuracyInMeters
  • LocationStatus
  • MovementThreshold
  • ReportInterval

The most commonly used method:

  • GetPositionAsync ()

And finaly two events:

  • PositionChanged
  • StatusChanged

The properties

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.
  • Hight, 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 achieve 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 take 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 in place.

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 Msdn Library.

Let's see how to use the services to retrieve the values of latitude is 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 present the initial project.

We on the left of the image, the graphic interface, where as you insert or controls from the Toolbox, or xaml, we will show a preview of what will our application. 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.

        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>
            
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="20"/>
                <ColumnDefinition Width="Auto"/>                
            </Grid.ColumnDefinitions>
            
            
            <TextBlock Grid.Row="0" Grid.Column="0" x:Name="tbkLatitude" Text="Latitude"/>
            <TextBlock Grid.Row="1" Grid.Column="0" x:Name="tbkLongitude" Text="Longitude"/>
            <TextBlock Grid.Row="0" Grid.Column="2" x:Name="tbkLatitudeValue"/>
            <TextBlock Grid.Row="1" Grid.Column="2" x:Name="tbkLongitudeValue"/>
            
            <Button Grid.Row="3" Grid.ColumnSpan="3" x:Name="btnFindCoordinate" Content="Find data" Tap="btnFindCoordinate_Tap"/>                        
        </Grid>

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

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

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

Created the necessary checks, we see this code what is needed to retrieve these values. Edit the code file, proceed with the F7 key, or in Solution Explorer going to expand the mainpage.XAML file until you find the MainPage.xaml.cs file in our case, the xaml file or if we develop in VbNet. Click with the mouse and be conducted within the code-behind file. Earlier we mentioned that Windows Runtime provides us the Geolocator, so the first thing to do is add the code into the file Namespace.

using Windows.Devices.Geolocation;

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

 var locator = new Geolocator();
 
 
            if (!locator.LocationStatus.Equals(PositionStatus.Disabled))
            {
                var position = await locator.GetGeopositionAsync();
                tbkLatitudeValue.Text = position.Coordinate.Latitude.ToString();
                tbkLongitudeValue.Text = position.Coordinate.Longitude.ToString();
            }
 
            else
            {
                MessageBox.Show("Service Geolocation not enabled!", AppResources.ApplicationTitle, MessageBoxButton.OK);
                return;
            }

How does it work? Declare a variable named type locator, is advisable Geolocator check status to verify that services are active, otherwise we will get an exception when trying to detect the location. This run going to 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 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 converted 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.

        private async void btnFindCoordinate_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            var locator = new Geolocator();
 
 
            if (!locator.LocationStatus.Equals(PositionStatus.Disabled))
            {
                var position = await locator.GetGeopositionAsync();
                tbkLatitudeValue.Text = position.Coordinate.Latitude.ToString();
                tbkLongitudeValue.Text = position.Coordinate.Longitude.ToString();
            }
 
            else
            {
                MessageBox.Show("Service Geolocation not enabled!", AppResources.ApplicationTitle, MessageBoxButton.OK);
                return;
            }
        }

Before proceeding with the application, debugging is and must enable 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 figure.

Open the file 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, 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.

Conclusion

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 which 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, the we'll explore each one.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here