We help IT Professionals succeed at work.

# Distance calculator using Google Maps API

on
Please let me know how I can calculate the walking and driving distances using Google Maps API.

If possible, please provide some sample code. Thanks!
Comment
Watch Question

## View Solution Only

HelpDesk / Programmer
CERTIFIED EXPERT

Commented:
here is the code i used to calculate the distance from two addresses
``````<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=PASTE_API_KEY" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
var map = null;
var geocoder = null;
var marker1=null;
var marker2=null;
var marker1_lat=null;
var marker2_lat=null;
var marker1_lon=null;
var marker2_lon=null;
var polyline=null;
{
if (GBrowserIsCompatible())
{
map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(47.4984056, 19.0407578), 13);
map.setUIToDefault();
geocoder = new GClientGeocoder();
}
}
{
map.clearOverlays();
polyline=null;
if (geocoder)
{
geocoder.getLatLng
(
function(point)
{
if (!point)
{
}
else
{
marker1 = new GMarker(point);
marker1_lat=marker1.getPoint().lat();
marker1_lon=marker1.getPoint().lng();
}
}
);
geocoder.getLatLng
(
function(point)
{
if (!point)
{
}
else
{
marker2 = new GMarker(point);
marker2_lat=marker2.getPoint().lat();
marker2_lon=marker2.getPoint().lng();
}
}
);
var polyOptions = {geodesic:true};
polyline = new GPolyline([
new GLatLng(marker1_lat, marker1_lon),
new GLatLng(marker2_lat, marker2_lon)
], "#ff0000", 10, 1, polyOptions);
var mark1=new GLatLng(marker1_lat, marker1_lon);
var mark2=new GLatLng(marker2_lat, marker2_lon);
var dist=document.getElementById("dist_lbl");
map.setCenter(polyline,10);
}//ifend

}//fugg end
function distance(lat1, lon1, lat2, lon2, unit) //the funtion that calculates the distance
{
var theta = lon1 - lon2;
if (dist > 1.0)
dist=1.0;
dist = Math.acos(dist);
var result = dist * 60 * 1.1515;
switch (unit.toUpperCase())
{
case "M": //mile
return result;
break;
case "K"://km
return result * 1.609344;
break;
case "N"://nautic mile
return result * 0.8684;
break;
default:
return result * 1.609344;
break;
}
}

{
return deg * Math.PI / 180;
}

{
return rad * 180 / Math.PI;
}

</script>
``````
in <body></body> put this code:
``````<center>
<br/>
<div id="dist_lbl"></div>
</center>
<br/>
<div id="map" style="width: 620px; height: 400px"></div>
``````

hope it helps
HelpDesk / Programmer
CERTIFIED EXPERT

Commented:
oh, and i forgot that you must add the following code to initialize the map: