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 thisServer 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 :
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.
Thanks man you just made things simpler for me. thank you very much