Introduction
Google Maps API V3 provides us different services like Direction, Distance Matrix, Geocoding
etc. to integrate Google map features directly on to your web site. These services can be integrated many ways like front end (JavaScript) or back end (C#. NET code behind).
So in this article I am going to discuss about integrating Google direction and geocoding services using C#. NET code behind.
Background
I have been looking at some online articles or some online sample codes for Google Maps API v3 XML web service integration using C# code behind, but I
could not find much information (may be my searching keywords didn't match with Google searching algorithm) on the net, so i have decided to write a little article
on my findings so far on my own research with Google Maps API v3.
Using the code
Distance Matrix?
Service that Google offers for us to get a driving distance from a post code to a post code. By default this service returns driving distance in KM, but if we customize request parameter like "units=imperial"
we can get the driving distance in miles:
public static double GetDrivingDistanceInMiles(string origin, string destination)
{
string url = @"http://maps.googleapis.com/maps/api/distancematrix/xml?origins=" +
origin + "&destinations=" + destination +
"&mode=driving&sensor=false&language=en-EN&units=imperial";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
WebResponse response = request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader sreader = new StreamReader(dataStream);
string responsereader = sreader.ReadToEnd();
response.Close();
XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(responsereader);
if (xmldoc.GetElementsByTagName("status")[0].ChildNodes[0].InnerText == "OK")
{
XmlNodeList distance = xmldoc.GetElementsByTagName("distance");
return Convert.ToDouble(distance[0].ChildNodes[1].InnerText.Replace(" mi", ""));
}
return 0;
}
Geocoding?
Service that Google offers for us to get geographic
coordinates information like latitude and longitude.
public double GetCoordinatesLat(string addresspoint)
{
using (var client = new WebClient())
{
string seachurl = "http://maps.google.com/maps/geo?q='" + addresspoint + "'&output=csv";
string[] geocodeInfo = client.DownloadString(seachurl).Split(',');
return (Convert.ToDouble(geocodeInfo[2]));
}
}
public double GetCoordinatesLng(string addresspoint)
{
using (var client = new WebClient())
{
string seachurl = "http://maps.google.com/maps/geo?q='" + addresspoint + "'&output=csv";
string[] geocodeInfo = client.DownloadString(seachurl).Split(',');
return (Convert.ToDouble(geocodeInfo[3]));
}
}
I hope this little article will help some one else in the community to get some very basic idea about integrating Google
Maps API into their web site,
please ask me any questions if there are and I will be happy to answer for it.
References