Google+ Followers


Get Updates Via Email

Enter your email address:

Delivered by FeedBurner

Thursday, 4 April 2013

Getting Distance and Traveling Time (Bus Mode) Details from Google Maps in ASP.NET C# using Google Maps API XML & XPath Webservice


1. In Design View Coding, add the Javascript Code in Head section to make an integration with Google Maps API Script.

    <script src=""

2. Add the Source and Destination functions inside script tags, which is indicating the locations

function Source() {
            try {
                var input = document.getElementById('TextBox1');
                var autocomplete = new google.maps.places.Autocomplete(input);
            catch (err) {
                // exception catching here

        function Destination() {
            try {
                var input = document.getElementById('TextBox2');
                var autocomplete = new google.maps.places.Autocomplete(input);
            catch (err) {
                // exception catching here;

3. Add dom event Listner Load function in window
        google.maps.event.addDomListener(window, 'load', Source);
        google.maps.event.addDomListener(window, 'load', Destination);  
4. Finally add these codes, in thecode behind page of Default.aspx.cs which uses Google Maps distancematrix webservice api to get the distance between the two or more Address, city Locations as well as Travelling Time of the two end points in different mode, Here I have used Vehicle Type mode as Bus;

    //Travel mode as Bus
    public void google_Distance_TravelTime_BusMode()
        //Declare variable to store XML result
        string xmlResult = null;

        //Pass request to google api with orgin and destination details
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("" + TextBox1.Text + "&destinations=" + TextBox2.Text + "&mode=Bus&language=us-en&sensor=false");

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

        //Get response as stream from httpwebresponse
        StreamReader resStream = new StreamReader(response.GetResponseStream());

        //Create instance for xml document

        XmlDocument doc = new XmlDocument();

        //Load response stream in to xml result
        xmlResult = resStream.ReadToEnd();

        //Load xmlResult variable value into xml documnet

        string output = "";

            //Get specified element value using select single node method and verify it return OK (success ) or failed
            if (doc.DocumentElement.SelectSingleNode("/DistanceMatrixResponse/row/element/status").InnerText.ToString().ToUpper() != "OK")
                Label2.ForeColor = System.Drawing.Color.Red;

                Label2.Text = "Invalid City Name please try again";

            //Get DistanceMatrixResponse element and its values
            XmlNodeList xnList = doc.SelectNodes("/DistanceMatrixResponse");
            foreach (XmlNode xn in xnList)
                if (xn["status"].InnerText.ToString() == "OK")
                    //Form a table and bind it orgin, destination place and return distance value, approximate duration
                    output = "<table align='center' width='600' cellpadding='0' cellspacing='0'>";
                    output += "<tr><td height='60' colspan='2' align='center'><b>Travel Details</b></td>";
                    output += "<tr><td height='40' width='30%' align='left'>Source</td><td align='left'>" + xn["origin_address"].InnerText.ToString() + "</td></tr>";
                    output += "<tr><td height='40' align='left'>Destination</td><td align='left'>" + xn["destination_address"].InnerText.ToString() + "</td></tr>";
                    output += "<tr><td height='40' align='left'>Travel Duration(apprx.) </td><td align='left'>" + doc.DocumentElement.SelectSingleNode("/DistanceMatrixResponse/row/element/duration/text").InnerText + "</td></tr>";
                    output += "<tr><td height='40' align='left'>Distance</td><td align='left'>" + doc.DocumentElement.SelectSingleNode("/DistanceMatrixResponse/row/element/distance/text").InnerText + "</td></tr>";
                    output += "</table>";

                    //finally bind it in the result label control

                    Label1.ForeColor = System.Drawing.Color.Green;
                    Label1.Text = doc.DocumentElement.SelectSingleNode("/DistanceMatrixResponse/row/element/distance/text").InnerText;
                    Label2.ForeColor = System.Drawing.Color.Green;
                    Label2.Text = doc.DocumentElement.SelectSingleNode("/DistanceMatrixResponse/row/element/duration/text").InnerText;
                    Label3.ForeColor = System.Drawing.Color.Green;
                    Label3.Text = output;
        catch (Exception ex)
            Label2.ForeColor = System.Drawing.Color.Red;
            Label2.Text = "Error during processing";

Screen Shots

1. Normal View

2. Enter Source Location: 

3. Enter Destination Location

4. Results : Distance  and Travelling  Time

5. Reset 

Design View Coding

Code Behind Coding

Happy Coding,
Kumaran K.

Show your Current Location in Google Maps using ASP.NET C# website and Google Maps API


  • Add this script tag inside <Head> section "
  • <script type="text/javascript"
  • src="">
  • </script>"
  • Inside this Script add your own Key value  [
  • key=AIzaSyByJmQq7PkPaznZUFsH7AesFNUz82U8iOc]  from Google Code
  • 1. Getting User Location function in Javascript coding
       function success(position) {
        var latitude = position.coords.latitude;
        var longitude = position.coords.longitude;
        var city = position.coords.locality;
        var myLatlng = new google.maps.LatLng(latitude, longitude);
        var myOptions = {
            center: myLatlng,
            zoom: 12,
            mapTypeId: google.maps.MapTypeId.SATELLITE
       2. Setting Marker in Google Maps

      var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
        var marker = new google.maps.Marker({
            position: myLatlng,
            title: "lat: " + latitude + " long: " + longitude
        var infowindow = new google.maps.InfoWindow({ content: "<b>User Address</b><br/> Latitude:" + latitude + "<br /> Longitude:" + longitude + "" });, marker);

      3. Geolocation to get Location , and calling the Javascript function

if (navigator.geolocation) {
    } else {
        alert("Geo Location is not supported on your current browser!");

   4. Load Google Maps inside map_canvas Div ID in Body Section of ASPX page

<div id="map_canvas" style="width: 800px; height: 400px">

Default.aspx Page