The Class GeocodeQuery 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 with other information, such as restaurants, hotels, places of interest and many other things. We talked about the class ReverseGeocodeQuery, that allows you to convert latitude and longitude values in an address. We continue in this third article on our path on geolocation services. This time we will see how to convert an address in coordinates, latitude and longitude, so as to view our location or type the name of a place or city to display within a control Nokia Maps.

The class GeocodeQuery

In addition to Geolocator and ReverseGeocodeQuery, which we find in the Namespace Windows.Devices.Geolocation and Microsoft.Phone.Maps.Services, we have another important class that the Windows runtime provides for us developers, the class GeocodeQuery. This class uses the same operating principle of the class ReverseGeocodeQuery, in other words that of conversion, but with the difference that in this case, is converted to an address in coordinates of latitude and longitude, then used for various purposes. Let us now analyze the class GeocodeQuery before using it in the code example.

As in previous articles, we see the main methods, properties and the only event available. For those who have followed the previous article, notice the differences with regard to the properties. We have the property SearchTerm.

The properties:

  • GeoCoordinate
  • SearchTerm

The most used method:

  • QueryAsync ()

The only event:

  • QueryCompleted

The properties

GeoCoordinate, unlike ReverseGeocodeQuery, should necessarily assign default values. Zero is recommended for latitude and longitude for the application to avoid crashing when the home position is searched. We will see in the example code how to do it.

SearchTerm is a property for insertion of a place or a point of interest, in other words the entire something is then converted into latitude and longitude. Once that is done the event QueryCompleted is fired. One thing we must pay attention to is to not put spaces in the search term, because otherwise it will fail, thus risking crashing the application. For error you wish to insert blank spaces, such as "Turi n" instead of Turin and not if you insert Novi Ligure, in the latter case, the search will be properly started because you will definitely find in the research phase because it is an Italian town, while in the first case the application will crash, precisely for the reasons described previously.

Methods

As for the class ReverseGeocodeQuery, the method QueryAsync(), when called, executes the query, but this time based on the time we entered and assigned to the property SearchTerm, having as a result, the coordinates of latitude and longitude. Note that although this method is called at the Async end, it is executed asynchronously, but being of type void, it is not based on the pattern Async / Await. For instance, a method void when it is executed, it returns a null, as is the case for example, if we call a method of type Int.


Events

Also in this case, the only event is QueryCompleted, executed when the query is finished; it returns all data relating to the address and those that serve us type GeoCoordinate, that are there will be the properties Latitude and Longitude, all 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. In addition to this we have:

  • Cancelled: bool type, that is useful to understand when and if 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 an address into latitude and longitude

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

Starting with the example that we created in the previous article, the application of the preceding test is structured as follows.



Using the class ReverseGeocodeQuery in the previous article, it was able to detect all the data that you see in the picture and through his property Information.Address, we order:

  • City
  • Country
  • CountryCode
  • HouseNumber
  • PostalCode
  • State
  • Street

At the moment this is the XAML code for the representation of the graphical interface.

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

As said before, we want to view a site in a control Nokia Maps. In this article I will not expand on how this control, we'll just see the attraction that we will enter into a TextBox control. First, we eliminate the previous XAML code and replace it with this the following.

  1. <!--ContentPanel - inserire ulteriore contenuto qui-->  
  2. <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">  
  3.     <Grid.RowDefinitions>  
  4.         <RowDefinition Height="*"/>  
  5.         <RowDefinition Height="Auto"/>  
  6.     </Grid.RowDefinitions>  
  7.   
  8.     <StackPanel>  
  9.         <StackPanel Orientation="Horizontal">  
  10.             <TextBlock Text="Insert a location" Margin="0,20,0,0"/>  
  11.             <TextBox x:Name="tbxCity" Width="300"/>  
  12.         </StackPanel>  
  13.   
  14.         <StackPanel>  
  15.             <Controls:Map x:Name="mapLocation" Height="442" Width="480"/>  
  16.         </StackPanel>  
  17.     </StackPanel>  
  18.   
  19.     <Button Grid.Row="1" x:Name="btnFindCoordinate" Content="Find data" Tap="btnFindCoordinate_Tap"/>  
  20. </Grid>  
  21. /Grid> 

Looking at the code, you will notice that we have a new control.

  1. <Controls:Map x:Name="mapLocation" Height="442" Width="480"/> 

This is the Nokia Maps control that we said before. There are two ways to put the control on the screen, or by dragging it from the toolbox and place it inside the Control Panel stack, in this way will be automatically imported the namespace necessary, we will find at the top inside the MainPage.xaml file.

  1. xmlns:Controls="clr-namespace:Microsoft.Phone.Maps.Controls;assembly=Microsoft.Phone.Maps" 

If you decide to write it manually, you must remember to introduce the namespace control over Nokia Maps. After this activity, if everything is written correctly, we will have a screen made up as follows.



From the picture, you can see that we first compared to a control of Nokia Maps. Now on to part of the code behind, we modify the code on the event tap of the button by calling a method named GetPosition().

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

Now for the code needed for the conversion from address to coordinates.

  1. public void GetPosition()  
  2. {  
  3.     var latitude = 0d;  
  4.     var longitude = 0d;  
  5.     var locator = new Geolocator();  
  6.     var geocodequery = new GeocodeQuery();  
  7.   
  8.     if (!locator.LocationStatus.Equals(PositionStatus.Disabled))  
  9.     {  
  10.         geocodequery.GeoCoordinate = new GeoCoordinate(0, 0);  
  11.         geocodequery.SearchTerm = tbxCity.Text;  
  12.         geocodequery.QueryAsync();  
  13.   
  14.         geocodequery.QueryCompleted += (sender, args) =>  
  15.         {  
  16.             if (!args.Result.Equals(null))  
  17.             {  
  18.                 var result =  args.Result.FirstOrDefault();  
  19.   
  20.                 latitude = result.GeoCoordinate.Latitude;  
  21.                 longitude = result.GeoCoordinate.Longitude;  
  22.   
  23.                 mapLocation.SetView(result.BoundingBox, Microsoft.Phone.Maps.Controls.MapAnimationKind.Parabolic);  
  24.             }  
  25.         };  
  26.   
  27.     }  
  28.   
  29.     else  
  30.     {  
  31.         MessageBox.Show("Service Geolocation not enabled!", AppResources.ApplicationTitle, MessageBoxButton.OK);  
  32.         return;  
  33.     }  

Analyze the code. Concerning the class Geolocator, compared to the example of the previous article nothing changes, everything remains unchanged.

The first part of this new line of code, here we declare a new object of type GeocodeQuery.

  1. var geocodequery = new GeocodeQuery(); 

The remaining part of the code.

  1. if (!locator.LocationStatus.Equals(PositionStatus.Disabled))  
  2.           {  
  3.               geocodequery.GeoCoordinate = new GeoCoordinate(0, 0);  
  4.               geocodequery.SearchTerm = tbxCity.Text;  
  5.               geocodequery.QueryAsync();  
  6.   
  7.               geocodequery.QueryCompleted += (sender, args) =>  
  8.               {  
  9.                   if (!args.Result.Equals(null))  
  10.                   {  
  11.                       var result =  args.Result.FirstOrDefault();  
  12.   
  13.                       latitude = result.GeoCoordinate.Latitude;  
  14.                       longitude = result.GeoCoordinate.Longitude;  
  15.   
  16.                       mapLocation.SetView(result.BoundingBox, Microsoft.Phone.Maps.Controls.MapAnimationKind.Parabolic);  
  17.                   }  
  18.               };  
  19.   
  20.           } 

Enhance the property geo-coordinates, passing as arguments dummy values. This is as said previously, serves as a starting point and for that it does not raise an exception during the search phase of the position, hereinafter called the method and 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 I<MapLocation>. The other changes from the previous article are these two lines of code to control Nokia Maps, both possibilities lead to the same end result. In other words, the search for the point of interest is entered into the TextBox control.

  1. mapLocation.Center = new GeoCoordinate(latitude, longitude);  
  2.                         mapLocation.SetView(result.BoundingBox, Microsoft.Phone.Maps.Controls.MapAnimationKind.Parabolic); 

In the first case, we have the property called Center. We need to go to this property an object of type GeoCoordinate together with the values of latitude and longitude returned after the event QueryCompleted was done.

In the second case, instead we have a method called SetView (). This is exactly a method that, as the property Center, is able to center the position typed within the map. This method is enhanced through the property BoundingBox, returned as the property Center after the execution of the event QueryCompleted in a collection of type I<MapLocation>, it represents a portion of a map including the latitude and longitude, can then be displayed within the control Nokia Maps, so an alternative to the property Center. The method SetView(), besides the property BoundingBox, if we wish, we can define another topic; it is a value enumerator MapAnimationKind, in other words a kind of animation during the research phase within the map.

We have the following three choices:

  • None
  • Linear
  • Parabolic

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 features section and activate it if you have not already done so, the Capability ID_CAP_MAP and ID_CAP_LOCATION as shown in the figure.



After this activity, we can finally debug. Pres the F5 key, start the application, that will initially be as shown in the figure. In my case I used a Nokia Lumia 820 for testing the example.



Now we type the name of a city, such as Turin or what that you want. Taking a tap on the Find data button, if all goes well, will start searching through the control Nokia Maps and see the center of the town on the map.





Conclusion

In this third article, we saw how to view a location within a control Nokia Maps, all thanks to the class GeocodeQuery. Again, in this article we are limited to only viewing, but you can do much, much more within the control in general with Nokia Maps and maps. From the next article, we will begin to explore and see everything that you can do, so stay tuned and develop, develop, develop.

Up Next
    Ebook Download
    View all
    Learn
    View all