JavaScript Calculate Distance Between Two Addresses

JavaScript Calculate Distance Between Two Addresses
JavaScript Calculate Distance Between Two Addresses

JavaScript Calculate Distance Between Two Addresses

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 : 


End Address : 
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 :

	Google Place
	
		#distance,#distance2,#time1,#time2{
			background: yellow;
width: 160px;
display: inline-block;
height: 15px;
		}
	


Start Address : 


End Address : 


Distance : - In Text Format Value  Only Numeric Value in Metres 


Time : - In Text Format Value  Only Numeric Value in Seconds 




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);




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

 

supercoders
A Journey Of Coding to Became a Best Software Developer