Welcome folks today in this blog post we will be calculating the distance and time between two locations using the google distance matrix
api in browser using javascript. All the full source code of the application is shown below.
Get Started
In order to get started you need to first of all enable the google distance matrix api
in the cloud console and then you need to create the api
key in the cloud console as shown below
Now make a index.html
file and copy paste the below code
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> </head> <body> <div class="container"> <div class="row"> <div class="jumbotron"> <h1>Time & Distance Calculator Between Two Locations & Addresses</h1> </div> <div class="col-md-12"> <form id="distance_form"> <div class="form-group"> <label>Origin: </label> <input class="form-control" id="from_places" placeholder="Enter a location" /> <input id="origin" name="origin" required="" type="hidden" /> </div> <div class="form-group"> <label>Destination: </label> <input class="form-control" id="to_places" placeholder="Enter a location" /> <input id="destination" name="destination" required="" type="hidden" /> </div> <input class="btn btn-primary" type="submit" value="Calculate" /> </form> <div id="result"> <ul class="list-group"> <li id="mile" class=" list-group-item d-flex justify-content-between align-items-center " > Distance In Mile : </li> <li id="kilo" class=" list-group-item d-flex justify-content-between align-items-center " > Distance is Kilo: </li> <li id="text" class=" list-group-item d-flex justify-content-between align-items-center " > IN TEXT: </li> <li id="minute" class=" list-group-item d-flex justify-content-between align-items-center " > IN MINUTES: </li> <li id="from" class=" list-group-item d-flex justify-content-between align-items-center " > FROM: </li> <li id="to" class=" list-group-item d-flex justify-content-between align-items-center " > TO: </li> </ul> </div> </div> </div> <br><br> </body> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script defer src="https://maps.googleapis.com/maps/api/js?libraries=places&language=en&key=##yourapikey##" type="text/javascript"></script> </html> |
As you can see we are importing the jquery library
cdn and also we are importing the google distance matrix api
library cdn and also we are passing the api key.
Here you need to replace your own api key in the above code.
Now we are using the bootstrap
form fields where we are displaying the result data. If you open the index.html
file inside the browser you will see the below output
And now we need to write the custom javascript
code to get the distance between two locations
using the google distance matrix api as shown below
script.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 |
$(function () { // add input listeners google.maps.event.addDomListener(window, "load", function () { var from_places = new google.maps.places.Autocomplete( document.getElementById("from_places") ); var to_places = new google.maps.places.Autocomplete( document.getElementById("to_places") ); google.maps.event.addListener( from_places, "place_changed", function () { var from_place = from_places.getPlace(); var from_address = from_place.formatted_address; $("#origin").val(from_address); } ); google.maps.event.addListener( to_places, "place_changed", function () { var to_place = to_places.getPlace(); var to_address = to_place.formatted_address; $("#destination").val(to_address); } ); }); // calculate distance function calculateDistance() { var origin = $("#origin").val(); var destination = $("#destination").val(); var service = new google.maps.DistanceMatrixService(); service.getDistanceMatrix( { origins: [origin], destinations: [destination], travelMode: google.maps.TravelMode.DRIVING, unitSystem: google.maps.UnitSystem.IMPERIAL, // miles and feet. // unitSystem: google.maps.UnitSystem.metric, // kilometers and meters. avoidHighways: false, avoidTolls: false, }, callback ); } // get distance results function callback(response, status) { if (status != google.maps.DistanceMatrixStatus.OK) { $("#result").html(err); } else { var origin = response.originAddresses[0]; console.log(origin); var destination = response.destinationAddresses[0]; console.log(destination); if (response.rows[0].elements[0].status === "ZERO_RESULTS") { $("#result").html( "Better get on a plane. There are no roads between " + origin + " and " + destination ); } else { var distance = response.rows[0].elements[0].distance; console.log(distance); var duration = response.rows[0].elements[0].duration; console.log(duration); console.log(response.rows[0].elements[0].distance); var distance_in_kilo = distance.value / 1000; // the kilom var distance_in_mile = distance.value / 1609.34; // the mile console.log(distance_in_kilo); console.log(distance_in_mile); var duration_text = duration.text; var duration_value = duration.value; $("#mile").html( `Distance in Miles: ${distance_in_mile.toFixed(2)}` ); $("#kilo").html( `Distance in Kilometre: ${distance_in_kilo.toFixed(2)}` ); $("#text").html(`Distance in Text: ${duration_text}`); $("#minute").html(`Distance in Minutes: ${duration_value}`); $("#from").html(`Distance From: ${origin}`); $("#to").text(`Distance to: ${destination}`); } } } // print results on submit the form $("#distance_form").submit(function (e) { e.preventDefault(); calculateDistance(); }); }); |
Now basically if you open the index.html
inside the browser you will see the below result as shown below