Getting To Where You Want To Be

Tags: Google, Map, Control, ASP.NET, Directions

In another tutorial I talk about geocoding, which is performed by the GoogleGeocoder class. This class has three general methods for geocoding:

  • Geocode
  • ReverseGeocode
  • GetDirections

Each of these methods returns a GoogleResult, which encapsulates the result of the request as well as any return values. Just like with any web service response it is prudent to verify the status of the operation. If the operation is successful and a result has been returned, its data can then be used.

Once you have verified the result, it is likely that you will be using it to show on a map. The returned data is not returned directly as overlays, because I did not want to make any assumptions about what it was to be used for, or indeed how it was going to be displayed. I wanted to leave it up to you to extract the data from the result and display it in your way, letting Intellisense and the documentation guide you. The result data is laid out in the same way Google returns the directions from its web service.

For the impatient among you who do not want to spend time reading documentation or read the Intellisense suggestions, here is a shortcut, that was added in version 5.2. The route can be passed to the constructor of a Polyline and it will perform the work of creating the polyline for you. Like so:


var geocoder = new GoogleGeocoder();
var result = geocoder.GetDirections("Bratislava, Slovakia", "Trnava, Slovakia");
if (result.Status == GeocodeStatus.OK && result.Directions != null)
	foreach (var routeLine in result.Directions.Routes.Select(route => new Polyline(route)))

As always, when using the geocoding service, then make sure you cache the results. First of all it speeds of rendering the page, but you also won't run into the situation where Google stops responding because you have exceeded your daily limit. The best practice is to do it once application wide and then reuse the result. I'll leave this up as to how it best suits your application.

Latest Tweets