How to calculate distance using Google API?


In this article, I am going to explain about how to calculate distance between origin and destination place using Google API . This code snippet is be used in travel related websites.

Description :


In most cases we need to calculate distance between two places when going to tour etc. Using Google API we can calculate distance easily. I have explained here in detail with all code details and auto complete extender place name etc.

Client side


I have placed two textboxes to collect orgin and destination place name from user. Using that two names calculate distance.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Google Distance Matrix</title>
<style type="text/css">
.style1
{
height: 30px;
}
</style>

<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"
type="text/javascript"></script>

<script type="text/javascript">
function OrginAutoComplete() {
try {
var input = document.getElementById('TextBox1');
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.setTypes('changetype-geocode');
}
catch (err) {
// alert(err);
}
}


function DestAutoComplete() {
try {
var input = document.getElementById('TextBox2');
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.setTypes('changetype-geocode');
}
catch (err) {
// alert(err);
}
}

google.maps.event.addDomListener(window, 'load', OrginAutoComplete);
google.maps.event.addDomListener(window, 'load', DestAutoComplete);
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<table cellpadding="0" cellspacing="0" align="center" width="700">
<tr>
<td colspan="2" height="40">
<b>Distance calculation using Google API</b>
</td>
</tr>
<tr>
<td class="style1">
Enter Orgin Place
</td>
<td class="style1">
<asp:TextBox ID="TextBox1" runat="server" Width="300"></asp:TextBox>
</td>
</tr>
<tr>
<td height="30">
Enter Destination Place
</td>
<td>
<asp:TextBox ID="TextBox2" runat="server" Width="300"></asp:TextBox>
</td>
</tr>
<tr>
<td colspan="2" align="center" height="60">
<asp:Button ID="btnSearch" runat="server" Text="Calculate Distance" OnClick="btnSearch_Click" />
</td>
</tr>
<tr>
<td colspan="2" align="center" height="40">
<br />
<br />
<asp:Label ID="lblResult" runat="server" Text=""></asp:Label>
</td>
</tr>
</table>
<br />
</div>
</form>
</body>
</html>

Client side design and Google Auto Complete is look like this
Images

Server side


In the server side I pass the origin and destination places to Google API and get back xml return data. From that return data I get that distance and approximate travel hours etc.

using System.Net;
using System.Xml;
using System.Data;
using System.IO;
using System.Xml.XPath;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
lblResult.Text = "";
}
protected void btnSearch_Click(object sender, EventArgs e)
{
//Declare variable to store XML result
string xmlResult = null;

//Pass request to google api with orgin and destination details
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://maps.googleapis.com/maps/api/distancematrix/xml?origins=" + TextBox1.Text + "&destinations=" + TextBox2.Text + "&mode=Car&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
doc.LoadXml(xmlResult);

string output = "";

try
{
//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")
{
lblResult.Text = "Invalid City Name please try again";
return;
}

//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'>Orgin Place</td><td align='left'>" + xn["origin_address"].InnerText.ToString() + "</td></tr>";
output += "<tr><td height='40' align='left'>Destination Place</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
lblResult.Text = output;
}
}
}
catch (Exception ex)
{
lblResult.Text = "Error during processing";
return;
}
}
}

Output :


Images

Source code:


Client Side: ASP.NET

Code Behind: C#

In this source file i have used to two pages

1) Default.aspx - Directly apply google distance calculation

2) Default2.aspx - Apply google distance calculation in master page and implement in default2.aspx page

Conclusion


I hope this code snippet is helping you to calculate distance between two places.


Attachments

  • Distance_Calculate_source (43960-7447-Distance-Calculate-source.rar)
  • Comments

    Guest Author: Ntokozo Nkosi08 Sep 2012

    Thanks man you just made things simpler for me. thank you very much

    Guest Author: sukumar13 Sep 2012

    Sir,

    This project nice.But this will be paid version or free version.

    Because I want this project sir.

    Help me.

    Guest Author: PaulH19 Sep 2012

    Brilliant article - saved me hours! Many thanks.

    Author: Ravindran25 Sep 2012 Member Level: Gold   Points : 1

    Thanks Sukumar amd PaulH,

    @sukumar

    It is free version i am using google api.

    The above project source is available here

    www.dotnetspider.com/attachments/Resources/43960-7447-Distance-Calculate-source.rar

    Guest Author: Aijaz29 Sep 2012

    i appreciate this post. i have been searching for such a post for last more than a month. Thanx a ton

    Guest Author: Kapil Kothari21 Feb 2013

    I am getting this error..Please help me..Its urgent..I have to deliver it by EOD today.

    The remote server returned an error: (407) Proxy Authentication Required." is appeared.

    Guest Author: Kapil Kothari21 Feb 2013

    I am getting this error..Please help me..Its urgent..I have to deliver it by EOD today.

    The remote server returned an error: (407) Proxy Authentication Required." is appeared.

    Guest Author: shah ishan08 Mar 2013

    How does it calculate the time .

    Guest Author: hongzai04 Apr 2013

    Thanks~~You save me and my group assignment xD

    Guest Author: Susheel K27 Apr 2013

    Thank You very Much, Very helpful suggestion.
    I am using this output results in a calculation for a round trip distance (i.e. Distance[Pune-> Mumbai] x 2). But the output from above API is String (i.e "250 KM") i am not able to multiply the output with an integer number,
    is there any way i can do that?

    Guest Author: Amit Kumar Sahu26 Nov 2014

    This code is Good but GOOGLE Map API Link-(HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://maps.googleapis.com/maps/api/distancematrix/xml?origins=" + TextBox1.Text + "&destinations=" + TextBox2.Text + "&mode=Car&language=us-en&sensor=false");
    )
    calculates distance only 2500 time in 24 hrs and It expires after limit and shows error msg like "your daily quota API has Exeeded". And after that it doesn't calculate distance between Location.



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: