The Class ReverseGeocodeQuery in Windows Phone 8

Introduction

As explained in the previous article, geolocation is one of the most frequently used features in the mobile and beyond. With it we are able to retrieve the location and information about where we are and use that in an application to obtain other information, such as restaurants, hotels, places of interest and many other scenarios. We continue in this second article upon our path of geolocation services. We will see how to convert the coordinates of latitude and longitude in an address, to be displayed in an application with all the information on where we are and use them in future articles within a control, Nokia Maps Nokia, and also an example of how to detect the weather conditions.

The class ReverseGeocodeQuery

Besides the class Geolocator that we find in the namespace Windows.Devices.Geolocation, we have another important class that the Windows Runtime provides for us developers, the class ReverseGeocodeQuery. If you think about it, when we develop an application that makes use of the maps above or want to provide the user more information on the site, such as country name, address and more, that's the class ReverseGeocodeQuery and what we need. We analyze the main methods, properties and the only events available as in the following.

The properties

  • GeoCoordinate
  • IsBusy

The most used method:

  • QueryAsync ()

The only event:

  • QueryCompleted

Properties

GeoCoordinate, here we enter the latitude and longitude to ensure that they are then converted into an address from the class ReverseGeocodeQuery, all through an object of type GeoCoordinate, then we will see in the example how to do it.

IsBusy, read-only property, that is useful if we need to know if the query and in preparation for the recovery of data.

Methods

The method QueryAsync (), when called, executes the query using the coordinates of latitude and longitude, note that this method is called albeit with Async end, it is executed asynchronously, but being of type void, not based on the pattern Async / Await. For instance, a method void when it is executed, it does not return a result, as is the case, for example if we call a method of type Int.

Events

The only event is QueryCompleted and is executed when the query is finished and returns all the data concerning the address, in an object of type IList <MapLocation>. It is exactly all the results that were found by the query enclosed in a collection, because they can also be more than one. To find the information we need to refer to the Result property. Besides this we have:

  • Cancelled: bool type, that is useful to understand when and if an asynchronous action has been canceled.
  • Error: also of type bool, that is useful in case you need an error during the execution of the query, in fact, from this property, you will get an object of type Exception AsyncCompletedEventArgs with the error that occurred.
  • Result: we have described before, in other words the query results in a collection of type IList <MapLocation>.
  • UserState: properties of type Object, it returns the unique identifier for the asynchronous task running.

Convert coordinates of latitude and longitude to an address

Until now, you've taken a quick overview of the class ReverseGeocodeQuery, in other words, a brief analysis of the methods, properties, most used, along with the unique event QueryCompleted. For more details on the subject leave the link to the official documentation of MSDN Library.

Continuing the example that we created in the previous article, for those who had not yet downloaded it, the download is available at this link. The application of the test to the previous article was structured as follows.



We have four TextBlock controls that were used to display the latitude and longitude using the tap on the Button control named Find data. Open the project with Visual Studio 2013; I remember that this example was created with the Professional version. In exploring solutions, double-click with the mouse on the MainPage.xaml file. In the GUI, go to delete all the controls from the main grid called ContentPanel and insert the following code.

  1. <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">  
  2.         <Grid.RowDefinitions>  
  3.             <RowDefinition Height="*"/>  
  4.             <RowDefinition Height="Auto"/>                  
  5.         </Grid.RowDefinitions>  
  6.        
  7.         <StackPanel Orientation="Horizontal">  
  8.             <StackPanel>  
  9.                 <TextBlock Text="City   "/>  
  10.                 <TextBlock Text="Country    "/>  
  11.                 <TextBlock Text="CountryCode    "/>  
  12.                 <TextBlock Text="HouseNumber    "/>  
  13.                 <TextBlock Text="PostalCode "/>  
  14.                 <TextBlock Text="State  "/>  
  15.                 <TextBlock Text="Street "/>  
  16.             </StackPanel>  
  17.                        
  18.             <StackPanel>  
  19.              <TextBlock x:Name="tbkCity"/>  
  20.              <TextBlock x:Name="tbkCountry"/>  
  21.                 <TextBlock x:Name="tbkCountryCode"/>  
  22.                 <TextBlock x:Name="tbkHouseNumber"/>  
  23.              <TextBlock x:Name="tbkPostalCode"/>  
  24.              <TextBlock x:Name="tbkState"/>  
  25.                 <TextBlock x:Name="tbkStreet"/>  
  26.             </StackPanel>  
  27.         </StackPanel>  
  28.        
  29.         <Button Grid.Row="1" x:Name="btnFindCoordinate" Content="Find data" Tap="btnFindCoordinate_Tap"/>                          
  30. </Grid> 

Were added other controls TextBlock, to view some of the most important properties, such as City, Country, House number and other data that we will see later. After entering the code xaml, our GUI will take this aspect.



From the image above, you can see that we added than before the TextBlock controls that can display all the necessary data where we find ourselves. Now on to part of the code behind, the first thing to do is add the namespace given below, necessary if we want to use the class ReverseGeocodeQuery.

  1. using Microsoft.Phone.Maps.Services; 

We modify the code on the event tap of the button, invoking an asynchronous method called GetAddress().

  1. private void btnFindCoordinate_Tap(object sender, System.Windows.Input.GestureEventArgs e)  
  2. {  
  3.    GetAddress();  

Now the code you need to search for information about the place we are.

  1. public async void GetAddress()  
  2. {  
  3.     var latitude = 0d;  
  4.     var longitude = 0d;  
  5.     var locator = new Geolocator();  
  6.     var reversegeocodequery = new ReverseGeocodeQuery();  
  7.   
  8.     if (!locator.LocationStatus.Equals(PositionStatus.Disabled))  
  9.     {  
  10.         var position = await locator.GetGeopositionAsync();  
  11.         latitude = position.Coordinate.Latitude;  
  12.         longitude = position.Coordinate.Longitude;  
  13.   
  14.   
  15.         reversegeocodequery.GeoCoordinate = new GeoCoordinate(latitude, longitude);  
  16.         reversegeocodequery.QueryAsync();  
  17.   
  18.         reversegeocodequery.QueryCompleted += (sender, args) =>  
  19.         {  
  20.             if (!args.Result.Equals(null))  
  21.             {  
  22.                 var result = args.Result.FirstOrDefault();  
  23.   
  24.                  tbkCity.Text = result.Information.Address.City;  
  25.                  tbkCountry.Text =  result.Information.Address.Country;  
  26.                  tbkCountryCode.Text =  result.Information.Address.CountryCode;  
  27.                  tbkHouseNumber.Text =  result.Information.Address.HouseNumber;  
  28.                  tbkPostalCode.Text =  result.Information.Address.PostalCode;  
  29.                  tbkState.Text =  result.Information.Address.State;  
  30.                  tbkStreet.Text =  result.Information.Address.Street;  
  31.             }  
  32.         };  
  33.   
  34.     }  
  35.   
  36.     else  
  37.     {  
  38.         MessageBox.Show("Service Geolocation not enabled!", AppResources.ApplicationTitle, MessageBoxButton.OK);  
  39.         return;  
  40.     }  

We will analyze the content. Concerning the class Geolocator, compared to the example of the previous article nothing changes, everything remains unchanged. The news part of this line of code, here we declare a new object of type ReverseGeocodeQuery.

  1. var reversegeocodequery = new ReverseGeocodeQuery(); 

The following is the remaining part of the code.

  1. reversegeocodequery.GeoCoordinate = new GeoCoordinate(latitude, longitude);  
  2. reversegeocodequery.QueryAsync();  
  3.   
  4. reversegeocodequery.QueryCompleted += (sender, args) =>  
  5. {  
  6.     if (!args.Result.Equals(null))  
  7.     {  
  8.         var result = args.Result.FirstOrDefault();  
  9.   
  10.          tbkCity.Text = result.Information.Address.City;  
  11.          tbkCountry.Text =  result.Information.Address.Country;  
  12.          tbkCountryCode.Text =  result.Information.Address.CountryCode;  
  13.          tbkHouseNumber.Text =  result.Information.Address.HouseNumber;  
  14.          tbkPostalCode.Text =  result.Information.Address.PostalCode;  
  15.          tbkState.Text =  result.Information.Address.State;  
  16.          tbkStreet.Text =  result.Information.Address.Street;  
  17.     }  
  18. }; 

Enhance the property geo-coordinates, passing as arguments the latitude and longitude as the class Geolocator noted and later called the method QueryAsync(). Finally we endorse the event QueryCompleted, executed when the query has been executed and completed, restoring all the data in a collection of type IList <MapLocation>. The data are stored in the Address property, we have the property City, Country, CountryCode, HouseNumber, PostalCode and State Street, or those of greater use, although in reality they are not the only ones, but we have others that can be used by intellisense. Visual Studio 2013 will show all the available values. Now that we have both the code and the GUI code-behind, it is time to run the application, but before you start debugging you need to activate the required capability. In exploring solutions expand the Properties folder and double-click with the mouse on the file WMAppManifest.xaml, go to the section functionality and activate the Capability ID_CAP_MAP, as shown in the figure.



After this activity, we can finally debug. Press the F5 key to start the application that will initially be as shown in the figure.



Taking a tap on the Find button and everything goes well; we will have all the address data on the basis of latitude and longitude is that the class Geolocator noted.



Conclusion

In this second article, we saw how to get latitude and longitude using other data on the site in which we find ourselves, all thanks to the class ReverseGeocedeQuery. In the next article, we'll have a look at the class GeocodeQuery, that has the same approach, with the difference that transforms the data to an address from latitude and longitude.


Similar Articles