JavaScript Calculate Distance Between Two Addresses

JavaScript Calculate Distance Between Two Addresses

 
javascript distance matrix api

In Previous Demo We See How To Use Auto Complete Location, Now From That Example I create a Another Demo Example For How To Calculate Distance Between Two Address.

 ( Note  : Address Must Be Exist in Google Autocomplete Address)

Let's Start!.

First You Need Api Key.

For New Users They Don't Know How To Get Api Key Please Visit this Link to Get YOUR API Key   

Link :  Api Key Link   

Step 1 : I create a html page with two input fields.
Start Address : <input type="text" placeholder="Start Address" id="startaddress">
<br>
End Address : <input type="text" placeholder="End Address" id="endaddress">
Step 2 : Adding a JavaScript function for Adding Google Auto Complete Location Event on Input Fields. On Our Page Ready I call this Function.
	function AutoComplete() {
                 //=============Input Fields 1 and Select it========
               var input1 = document.getElementById('startaddress');
            //===============adding google location search event=================
            new google.maps.places.Autocomplete(input1);

                 //=============Input Fields 2 and Select it========
               var input2 = document.getElementById('endaddress');
            //===============adding google location search event=================
            new google.maps.places.Autocomplete(input2);
	}

//===========================Call The Autocomplete Function of Our Page Ready===============
	    google.maps.event.addDomListener(window, 'load', AutoComplete);
Step 3 : Adding Distance Matrix JavaScript Api for Calcuating Distance and Time Taken.
function getDistance(){

	  var distanceService = new google.maps.DistanceMatrixService();
        distanceService.getDistanceMatrix({
                origins: [document.getElementById('startaddress').value],
                destinations: [document.getElementById('endaddress').value],
                travelMode: "DRIVING",
                unitSystem: google.maps.UnitSystem.METRIC,
                durationInTraffic: true,
                avoidHighways: false,
                avoidTolls: false
            },
            function (response, status) {
                if (status !== google.maps.DistanceMatrixStatus.OK) {
                    console.log('Error:', status);
                } else {
                    console.log(response);
                   //=======================Our Text View Where i Display Distance and Time Values===================
                    document.getElementById('distance').innerHTML=response.rows[0].elements[0].distance.text;
                    document.getElementById('distance2').innerHTML=response.rows[0].elements[0].distance.value;
                    document.getElementById('time1').innerHTML=response.rows[0].elements[0].duration.text;
                    document.getElementById('time2').innerHTML=response.rows[0].elements[0].duration.value;

                }
            });
    }
Complete Example Code :
<!DOCTYPE html>
<html>
<head>
	<title>Google Place</title>
	<style type="text/css">
		#distance,#distance2,#time1,#time2{
			background: yellow;
width: 160px;
display: inline-block;
height: 15px;
		}
	</style>
</head>
<body>
Start Address : <input type="text" placeholder="Start Address" id="startaddress">
<br>
End Address : <input type="text" placeholder="End Address" id="endaddress">
<br>
Distance : - In Text Format Value <span id="distance"></span> Only Numeric Value in Metres <span id="distance2"></span>
<br>
Time : - In Text Format Value <span id="time1"></span> Only Numeric Value in Seconds <span id="time2"></span>

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

function getDistance(){
	
	  var distanceService = new google.maps.DistanceMatrixService();
        distanceService.getDistanceMatrix({
                origins: [document.getElementById('startaddress').value],
                destinations: [document.getElementById('endaddress').value],
                travelMode: "DRIVING",
                unitSystem: google.maps.UnitSystem.METRIC,
                durationInTraffic: true,
                avoidHighways: false,
                avoidTolls: false
            },
            function (response, status) {
                if (status !== google.maps.DistanceMatrixStatus.OK) {
                    console.log('Error:', status);
                } else {
                    console.log(response);
                    document.getElementById('distance').innerHTML=response.rows[0].elements[0].distance.text;
                    document.getElementById('distance2').innerHTML=response.rows[0].elements[0].distance.value;
                    document.getElementById('time1').innerHTML=response.rows[0].elements[0].duration.text;
                    document.getElementById('time2').innerHTML=response.rows[0].elements[0].duration.value;

                }
            });
    }


	function AutoComplete() {
                 //=============Input Fields 1 and Select it========
               var input1 = document.getElementById('startaddress');
            //===============adding google location search event=================
            new google.maps.places.Autocomplete(input1);

                 //=============Input Fields 2 and Select it========
               var input2 = document.getElementById('endaddress');
            //===============adding google location search event=================
            new google.maps.places.Autocomplete(input2);
	}

//======================Register Focus out Listener on Input Fields so we calculate distance and Time
document.getElementById("startaddress").addEventListener("focusout", getDistance);
document.getElementById("endaddress").addEventListener("focusout", getDistance);



//===========================Call The Autocomplete Function of Our Page Ready===============
	    google.maps.event.addDomListener(window, 'load', AutoComplete);

</script>
</body>
</html>

Note : I Calculating Time For DRIVING you can this values by WALKING,BICYCLING. Need To Change Here Only : - travelMode: "DRIVING",


 
Previous Post
Next Post

post written by:

0 comments: