Calculate Distance between two points, Get Driving Time – Advanced Distance Finder Tutorial

19 Apr

So you need to find distance between two places on the map and the shortest route. You need to get the driving time between these places

Demo              Download

<title>Distance finder</title>
<meta type="<a>description</a>" content="<a>Find the distance between two .</a>"/>

<script type="<a>text/javascript</a>" src="<a href="view-source:"></a>"></script>
<script type="<a>text/javascript</a>">

	var location1;
	var location2;

	var address1;
	var address2;

	var latlng;
	var geocoder;
	var map;

	var distance;

	// finds the coordinates for the two locations and calls the showMap() function
	function initialize()
		geocoder = new google.maps.Geocoder(); // creating a new geocode object

		// getting the two address values
		address1 = document.getElementById("address1").value;
		address2 = document.getElementById("address2").value;

		// finding out the coordinates
		if (geocoder)
			geocoder.geocode( { 'address': address1}, function(results, status)
				if (status == google.maps.GeocoderStatus.OK)
					//location of first address (latitude + longitude)
					location1 = results[0].geometry.location;
				} else
					alert("Geocode was not successful for the following reason: " + status);
			geocoder.geocode( { 'address': address2}, function(results, status)
				if (status == google.maps.GeocoderStatus.OK)
					//location of second address (latitude + longitude)
					location2 = results[0].geometry.location;
					// calling the showMap() function to create and show the map
				} else
					alert("Geocode was not successful for the following reason: " + status);

	// creates and shows the map
	function showMap()
		// center of the map (compute the mean value between the two locations)
		latlng = new google.maps.LatLng((,(location1.lng()+location2.lng())/2);

		// set map options
			// set zoom level
			// set center
			// map type
		var mapOptions =
			zoom: 1,
			center: latlng,
			mapTypeId: google.maps.MapTypeId.HYBRID

		// create a new map object
			// set the div id where it will be shown
			// set the map options
		map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

		// show route between the points
		directionsService = new google.maps.DirectionsService();
		directionsDisplay = new google.maps.DirectionsRenderer(
			suppressMarkers: true,
			suppressInfoWindows: true
		var request = {
			travelMode: google.maps.DirectionsTravelMode.DRIVING
		directionsService.route(request, function(response, status)
			if (status == google.maps.DirectionsStatus.OK)
				distance = "The distance between the two points on the chosen route is: "+response.routes[0].legs[0].distance.text;
				distance += "<br/>The aproximative driving time is: "+response.routes[0].legs[0].duration.text;
				document.getElementById("distance_road").innerHTML = distance;

		// show a line between the two points
		var line = new google.maps.Polyline({
			map: map,
			path: [location1, location2],
			strokeWeight: 7,
			strokeOpacity: 0.8,
			strokeColor: "#FFAA00"

		// create the markers for the two locations
		var marker1 = new google.maps.Marker({
			map: map,
			position: location1,
			title: "First location"
		var marker2 = new google.maps.Marker({
			map: map,
			position: location2,
			title: "Second location"

		// create the text to be shown in the infowindows
		var text1 = '<div id="content">'+
				'<h1 id="firstHeading">First location</h1>'+
				'<div id="bodyContent">'+
				'<p>Coordinates: '+location1+'</p>'+
				'<p>Address: '+address1+'</p>'+

		var text2 = '<div id="content">'+
			'<h1 id="firstHeading">Second location</h1>'+
			'<div id="bodyContent">'+
			'<p>Coordinates: '+location2+'</p>'+
			'<p>Address: '+address2+'</p>'+

		// create info boxes for the two markers
		var infowindow1 = new google.maps.InfoWindow({
			content: text1
		var infowindow2 = new google.maps.InfoWindow({
			content: text2

		// add action events so the info windows will be shown when the marker is clicked
		google.maps.event.addListener(marker1, 'click', function() {,marker1);
		google.maps.event.addListener(marker2, 'click', function() {,marker1);

		// compute distance between the two points
		var R = 6371;
		var dLat = toRad(;
		var dLon = toRad(location2.lng()-location1.lng());

		var dLat1 = toRad(;
		var dLat2 = toRad(;

		var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
				Math.cos(dLat1) * Math.cos(dLat1) *
				Math.sin(dLon/2) * Math.sin(dLon/2);
		var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
		var d = R * c;

		document.getElementById("distance_direct").innerHTML = "<br/>The distance between the two points (in a straight line) is: "+d;

	function toRad(deg)
		return deg * Math.PI/180;


<body bgcolor="<a>#eeeeee</a>">
	<div id="<a>form</a>" style="<a>width:100%; height:20%</a>">
		<table align="<a>center</a>" valign="<a>center</a>">
				<td colspan="<a>7</a>" align="<a>center</a>"><b>Find the distance between two locations</b></td>
				<td colspan="<a>7</a>">&nbsp;</td>
				<td>First address:</td>
				<td><input type="<a>text</a>" name="<a>address1</a>" id="<a>address1</a>" size="<a>50</a>"/></td>
				<td>Second address:</td>
				<td><input type="<a>text</a>" name="<a>address2</a>" id="<a>address2</a>" size="<a>50</a>"/></td>
				<td colspan="<a>7</a>">&nbsp;</td>
				<td colspan="<a>7</a>" align="<a>center</a>"><input type="<a>button</a>" value="<a>Show</a>" onclick="<a>initialize();</a>"/></td>
	<center><div style="<a>width:100%; height:10%</a>" id="<a>distance_direct</a>"></div></center>
	<center><div style="<a>width:100%; height:10%</a>" id="<a>distance_road</a>"></div></center>

	<center><div id="<a>map_canvas</a>" style="<a>width:70%; height:54%</a>"></div></center>

Posted by on April 19, 2012 in Geo Programming, JavaScript


Tags: , ,

4 responses to “Calculate Distance between two points, Get Driving Time – Advanced Distance Finder Tutorial

  1. Lucretia

    May 13, 2013 at 5:26 am

    Hi there! I could have sworn I’ve visited this web site before but after looking at many of the posts I realized it’s new to me.
    Anyhow, I’m definitely happy I found it and I’ll be bookmarking
    it and checking back frequently!

    • Rajitha

      May 13, 2013 at 1:59 pm

      At codezone4, we ‘re really dynamic. So is our site. More new post categories ‘re coming in the near future. Are you interested in OpenLayers, MapServer or Codeigniter? Then, stay in touch with us.

  2. Zaheer Abbas

    September 1, 2015 at 2:41 am

    Demo is not working

  3. Zaheer Abbas

    September 1, 2015 at 2:52 am

    Showing distance between two points wrong…
    The aproximative driving time is Also showing wrong…


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: