Introduction

As explained in the previous article , geolocation is one of the most frequently used features whilst out and about, With it we are able to retrieve the location and information about the place in which we find ourselves. Applications may obtain other information, such as nearby restaurants, places of interest and people. We talked about the class ReverseGeocodeQuery, which allows you to convert latitude and longitude values ??into an address.

This third article continues along our path exploring geolocation services. We will see how to convert from a latitude and longitude address, so as to view our location or type the name of a place or city to display within a Nokia Maps control.

 


The GeocodeQuery Class

In addition to Geolocator and ReverseGeocodeQuery from Windows.Devices.Geolocation and Microsoft.Phone.Map.Services, Windows Runtime provides another important class - GeocodeQuery. This latter operates in a similar manner to ReverseGeocodeQuery, in that it does conversion. The notable difference being it converts to latitude and longitude co-ordinates. Let us now analyze the class GeocodeQuery before using it in the example we have already seen in the previous articles. If you haven't already downloaded the sample this is available from this link .

As in previous articles, we see the main methods, properties, and the only event available. For those who have followed previous article , notice of 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, recommended zero for latitude and longitude, in order to avoid that the application to crash at the time when the home position search. We will see in the example code how to do it.

SearchTerm, this property through the insertion of a place or a point of interest, means that the whole is then converted into latitude and longitude once that is done the event QueryCompleted. One thing to which we must pay attention, you do not put spaces in the search term, because in this case will fail, thus risking crashing the application. For error you wish to insert blank spaces, such as Turi n or 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 called 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 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, where there will be the properties Latitude and Longitude, the 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 , 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 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.

<!--ContentPanel - inserire ulteriore contenuto qui--> 
 <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>

 

As mentioned 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 below:

 

<!--ContentPanel - inserire ulteriore contenuto qui--> 
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"
 <Grid.RowDefinitions
  <RowDefinition Height="*"/> 
  <RowDefinition Height="Auto"/> 
 </Grid.RowDefinitions
 <StackPanel
  <StackPanel Orientation="Horizontal"
   <TextBlock Text="Insert a location" Margin="0,20,0,0"/> 
   <TextBox x:Name="tbxCity" Width="300"/> 
  </StackPanel
  <StackPanel
   <Controls:Map x:Name="mapLocation" Height="442" Width="480"/> 
  </StackPanel
 </StackPanel
 <Button Grid.Row="1" x:Name="btnFindCoordinate" Content="Find data" Tap="btnFindCoordinate_Tap"/> 
 </Grid
</Grid>
 

 

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

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

 

This is the Nokia Maps control that we mentioned 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.

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().

private void btnFindCoordinate_Tap( object sender, System.Windows.Input.GestureEventArgs e) 
 GetPosition(); 
}

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

public void GetPosition() 
 var latitude = 0d; 
 var longitude = 0d; 
 var locator = new Geolocator(); 
 var geocodequery = new GeocodeQuery(); 
 if (!locator.LocationStatus.Equals(PositionStatus.Disabled)) 
 
  geocodequery.GeoCoordinate = new GeoCoordinate(0, 0); 
  geocodequery.SearchTerm = tbxCity.Text; 
  geocodequery.QueryAsync(); 
  geocodequery.QueryCompleted += (sender, args) => 
  
   if (!args.Result.Equals(null)) 
   
   var result = args.Result.FirstOrDefault(); 
   latitude = result.GeoCoordinate.Latitude; 
   longitude = result.GeoCoordinate.Longitude; 
   mapLocation.SetView(result.BoundingBox, Microsoft.Phone.Maps.Controls.MapAnimationKind.Parabolic); 
   
  }; 
 
 else 
 {  
  MessageBox.Show("Service Geolocation not enabled!", AppResources.ApplicationTitle, MessageBoxButton.OK); 
  return
 
}

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.

var geocodequery = new GeocodeQuery();

 

The remaining part of the code.

if (!locator.LocationStatus.Equals(PositionStatus.Disabled)) 
 geocodequery.GeoCoordinate = new GeoCoordinate(0, 0); 
 geocodequery.SearchTerm = tbxCity.Text; 
 geocodequery.QueryAsync(); 
   
 geocodequery.QueryCompleted += (sender, args) => 
 
  if (!args.Result.Equals(null)) 
  
  var result = args.Result.FirstOrDefault(); 
  latitude = result.GeoCoordinate.Latitude; 
  longitude = result.GeoCoordinate.Longitude; 
  mapLocation.SetView(result.BoundingBox, Microsoft.Phone.Maps.Controls.MapAnimationKind.Parabolic); 
  
 }; 
}

Enhance the property geo-coordinates, passing as arguments dummy values. This as mentioned previously, serves as a starting point and for that it does not an exception is raised 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 entered into the TextBox control.

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

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

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 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 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. F5 key, start the application, which will initially be as shown in the figure. In my case I used for testing the example, a Nokia Lumia 820.

 

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 developed, developed, developed.