Click here to Skip to main content
15,881,248 members
Articles / Mobile Apps / Windows Phone 7

The class ReverseGeocodeQuery in Windows Phone 8.

Rate me:
Please Sign up or sign in to vote.
4.70/5 (7 votes)
31 Aug 2014CPOL6 min read 16.1K   125   11   2
As explained in the previous article, the 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 the place in which we find ourselves, and used by an application to have otherinformation, such as restaurant

Introduction.

As explained in the previous article, the 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 the place in which we find ourselves, and used by an application to have other information, such as restaurants, hotels, places of interest and many other scenarios. We continue in this second article, our path on geolocation services, we will see how to convert the coordinates of latitude, longitude is in an address, so 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 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 give 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 event available:
 

The properties:

            • GeoCoordinate
            • IsBusy


The most used method:

            QueryAsync ()
 

The only event:

            QueryCompleted


The properties.

GeoCoordinate, here we enter the latitude longitude is 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, which 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 not returns any result, as is the case for example, if we call a method of type Int.

 

Events.

The only event QueryCompleted, 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, which is useful to understand when and if asynchronous action has been canceled.
Error: also of type bool, which 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 latitude longitude is in 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, 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, which were used to display the latitude longitude is 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.

XML
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
       <Grid.RowDefinitions>
              <RowDefinition Height="*"/>
              <RowDefinition Height="Auto"/>
       </Grid.RowDefinitions>


       <StackPanel Orientation="Horizontal">
              <StackPanel>
                     <TextBlock Text="City   "/>
                     <TextBlock Text="Country    "/>
                     <TextBlock Text="CountryCode    "/>
                     <TextBlock Text="HouseNumber    "/>
                     <TextBlock Text="PostalCode "/>
                     <TextBlock Text="State  "/>
                     <TextBlock Text="Street "/>
       </StackPanel>


        <StackPanel>
                     <TextBlock x:Name="tbkCity"/>
                     <TextBlock x:Name="tbkCountry"/>
                     <TextBlock x:Name="tbkCountryCode"/>
                     <TextBlock x:Name="tbkHouseNumber"/>
                     <TextBlock x:Name="tbkPostalCode"/>
                     <TextBlock x:Name="tbkState"/>
                     <TextBlock x:Name="tbkStreet"/>
              </StackPanel>
       </StackPanel>

       <Button Grid.Row="1" x:Name="btnFindCoordinate" Content="Find data" Tap="btnFindCoordinate_Tap"/>

</Grid>

Were added other controls TextBlock, to view some of the most important properties, such as City, Country, House number and other data which 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 TextBlock controls that can display all the necessary data on the place in which 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.

C#
using Microsoft.Phone.Maps.Services;

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

C#
private void btnFindCoordinate_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
   GetAddress();
}

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

C#
public async void GetAddress()
{
    var latitude = 0d;
    var longitude = 0d;
    var locator = new Geolocator();
    var reversegeocodequery = new ReverseGeocodeQuery();


    if (!locator.LocationStatus.Equals(PositionStatus.Disabled))
    {
        var position = await locator.GetGeopositionAsync();
        latitude = position.Coordinate.Latitude;
        longitude = position.Coordinate.Longitude;
        reversegeocodequery.GeoCoordinate = new GeoCoordinate(latitude, longitude);
        reversegeocodequery.QueryAsync();
        reversegeocodequery.QueryCompleted += (sender, args) =>

        {
            if (!args.Result.Equals(null))
            {
                var result = args.Result.FirstOrDefault();
                 tbkCity.Text = result.Information.Address.City;
                 tbkCountry.Text =  result.Information.Address.Country;
                 tbkCountryCode.Text =  result.Information.Address.CountryCode;
                 tbkHouseNumber.Text =  result.Information.Address.HouseNumber;
                 tbkPostalCode.Text =  result.Information.Address.PostalCode;
                 tbkState.Text =  result.Information.Address.State;
                 tbkStreet.Text =  result.Information.Address.Street;
            }
        };
    }

    else
    {
        MessageBox.Show("Service Geolocation not enabled!", AppResources.ApplicationTitle, MessageBoxButton.OK);
        return;
    }
}

We are going to 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.

C#
var reversegeocodequery = new ReverseGeocodeQuery();

The remaining part of the code.

C#
reversegeocodequery.GeoCoordinate = new GeoCoordinate(latitude, longitude);
reversegeocodequery.QueryAsync();


reversegeocodequery.QueryCompleted += (sender, args) =>
{
    if (!args.Result.Equals(null))
    {
         var result = args.Result.FirstOrDefault();
         tbkCity.Text = result.Information.Address.City;
         tbkCountry.Text =  result.Information.Address.Country;
         tbkCountryCode.Text =  result.Information.Address.CountryCode;
         tbkHouseNumber.Text =  result.Information.Address.HouseNumber;
         tbkPostalCode.Text =  result.Information.Address.PostalCode;
         tbkState.Text =  result.Information.Address.State;
         tbkStreet.Text =  result.Information.Address.Street;
    }
};

Enhance the property geo-coordinates, passing as arguments the latitude longitude is that 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 the 'intellisense, Visual Studio 2013 will show all 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. F5 key, start the application, which 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 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 take a look at the class GeocodeQuery, which has the same approach, with the difference that transforms the data to an address in coordinates latitude longitude is.

License

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



Comments and Discussions

 
GeneralMy vote of 5 Pin
Santhakumar M23-Nov-15 3:00
professionalSanthakumar M23-Nov-15 3:00 
GeneralMy vote of 5 Pin
Volynsky Alex1-Sep-14 12:30
professionalVolynsky Alex1-Sep-14 12:30 
Nice!

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.