Sunday, November 14, 2010

How to call Google MAP Webservice API from asp.net, call Geocoding Map API Webservice from asp.net

How the necessities arise?

Necessity is mother of invention.

I was assigned a task to develop a restaurant portal.

The basic aim behind creation of this project is to have a marketplace for all restaurant owner or hotel business, and provide end user with integrative google map services so that they visualize realtime.

If we are supposed to insert a simple google map, then we just have to insert a piece javascript code, and boom you are done.

But in my project, I have requirement where different restaurant/hotel owner register and give us their details and addresses.

So, What is Google Map API?

The Google Maps API lets you embed Google Maps in your own web pages with JavaScript. The API provides a number of utilities for manipulating maps and adding content to the map through a variety of services, allowing you to create robust maps applications on your website.

All map related functionalities can be achieved as seen on http://maps.google.com/

Then what was hurdle for me in using Map API?

These are the pure JavaScript code..!! You can develop whatever rich Map application you wanted to develop by writing piece of JavaScript codes.

Actually to host a map on your page, you need to have two parameters, Latitude & Longitude. But how do I get lat. and long. from server side scripting?

But I had no idea how to call Google Map API from C#/VB.NET.

So for my project, as usual, I start googling to find out my piece of sweet.

After searching for couple of hours, I come across this good article.

http://webcodeblog.com/2010/04/24/obtain-latitude-and-longitude-co-ordinates-for-an-address-using-asp-net-and-the-google-maps-api/

Here the author explained the how to obtain the latitude and longitude co-ordinates for an address using the Google Maps API.

But again here, it is pure JavaScript that utilize Google Map API to get lat & long of any address. But my problem is still there?

Hurrray….. I found the solution

Then accidently I come to across Google Maps API Web Services.

It is basically Maps API Web Services, a collection of HTTP interfaces to Google services providing geographic data for your maps applications.

In the documentation (http://code.google.com/apis/maps/documentation/webservices/),

I see that you can utilize Google Map API web service by making HTTP request to a specific URL, providing necessary parameters with URL. Which in return, gives a response in desired format.

You can get response inform of JSON or XML.

Say for e.g. it can be called like this URL

http://maps.google.com/maps/geo?q=khandala, maharashtra&output=xml&key=xxxxxxxxxxxxxx

Paste it into your browser and you will receive a XML response.

Immediately, I get one "Mantos (Dimag ki batti jala de)" and found a clue J

I thought why not to develop a library that make a call to this URL and parse the returned output to get lat & long…!!?

So for that purpose I write this library.

Obviously, before doing all these, you will need to register with Google Map API and get a key so that you can utilize their API.

Sign up and get a Google Maps API Key.  You will need one for the domain name of where you will be hosting the map.  You can get your API Key from here (http://code.google.com/apis/maps/signup.html)

Following is the complete code that I used to call Google Map Geocoding API from Asp.net.

All you have to do Is to just create a class file and paste the following code. And you are ready to call Google Map Geocoding API.

How to call Geocoding API from Asp.net?

Step 1

/// Resolve addresses into latitude/longitude coordinates using Google MAP API webservices

public static class Geocoder{

private static string _GoogleMapsKey = Config.getAppSetting("GoogleMapsKey");

/// Google.com Geocoder

/// Url request to

/// http://maps.google.com/maps/geo?q=your address&output=xml&key=xxxxxxxxxxxxxx

public static Geolocation? ResolveAddress(string query)

{

if (string.IsNullOrEmpty(_GoogleMapsKey))

_GoogleMapsKey = ConfigurationManager.AppSettings["GoogleMapsKey"];


string url = "http://maps.google.com/maps/geo?q={0}&output=xml&key=" + _GoogleMapsKey;

url = String.Format(url, query);

XmlNode coords = null;

try{

string xmlString = GetUrl(url);

XmlDocument xd = new XmlDocument();

xd.LoadXml(xmlString);

XmlNamespaceManager xnm = new XmlNamespaceManager(xd.NameTable);

coords = xd.GetElementsByTagName("coordinates")[0];

}


catch { }

Geolocation? gl = null;

if (coords != null){

string[] coordinateArray = coords.InnerText.Split(',');

if (coordinateArray.Length >= 2)

{

gl = new Geolocation(Convert.ToDecimal(coordinateArray[1].ToString()), Convert.ToDecimal(coordinateArray[0].ToString()));

}

}


return gl;

}


public static Geolocation? ResolveAddress(string address, string city, string state, string postcode, string country)

{

return ResolveAddress(address + "," + city + "," + state + "," + postcode + " " + country);

}

///
<summary>

/// Retrieve a Url via WebClient

private static string GetUrl(string url)

{

string result = string.Empty;

System.Net.WebClient Client = new WebClient();

using (Stream strm = Client.OpenRead(url))

{

StreamReader sr = new StreamReader(strm);

result = sr.ReadToEnd();

}


return result;

}

}


public struct Geolocation

{

public decimal Lat;


public decimal Lon;


public Geolocation(decimal lat, decimal lon)

{

Lat = lat;

Lon = lon;

}


public override string ToString()

{

return "Latitude: " + Lat.ToString() + " Longitude: " + Lon.ToString();

}

public string ToQueryString()

{

return "+to:" + Lat + "%2B" + Lon;

}

}

Step 2

Now, you just need to put a key in AppSetting section that hold your Google Map API key.

Step 3

I have provided 2 overloaded methods to call Geocoding Map API Webservice, named ResolveAddress.

Say for e.g. you can call method like this.

Geocoder.ResolveAddress("University road","rajkot","gujarat","","India")

I hope this will solve your purpose, those who wanted to develop Geocoding application, those who want to access Google Map Webservice API from c#/vb.net.

Happy programming…

 

No comments: