Welcome folks today in this blog post we will be building a google maps
distance and time calculator between two locations
using the distance matrix
and directions api in browser. All the full source code of the application is shown below.
LIVE DEMO
Get Started
In order to get started you need to make an index.html
file and copy paste the following 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 |
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Distances btn two cities App</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <link href="App.css" rel="stylesheet" /> </head> <body> <div class="container"> <h1>Find The Distance Between Two Places.</h1> <form class="form-horizontal"> <div class="form-group"> <label for="from"></label> <input type="text" id="from" placeholder="Origin" class="form-control"> </div> <div class="form-group"> <label for="to"></label> <input type="text" id="to" placeholder="Destination" class="form-control"> </div> </form> <div class="form-group"> <button class="btn btn-info btn-lg" onclick="calcRoute();">Calculate</button> </div> </div> <div class="container-fluid"> <div id="output"> </div> <div id="googleMap"> </div> </div> </div> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="https://maps.googleapis.com/maps/api/js?key=##yourapikey##&libraries=places"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script src="Main.js"></script> </body> </html> |
As you can see we have two input fields where we will be taking the location
of the origin
and the destination
and then we have the calculate button to find the distance
and time
between two locations. And also at the bottom we will be showing the directions
and routes on the google map using the directions
api. Here you need to replace your own api key
from google cloud console and also enable all the apis
needed as shown below
And now we need to make the App.css
file and copy paste the below css
styles for this web application
App.css
1 2 3 4 5 6 7 8 9 10 11 12 13 |
/*map*/ #googleMap { width: 80%; height: 400px; margin: 10px auto; } /*output box*/ #output { text-align: center; font-size: 2em; margin: 20px auto; } |
Now guys we will be writing the javascript
code for this application. Just create the Main.js
file and copy paste the following code.
First of all we will be adding the autocomplete
to the location fields
so that user can easily write the address
or location
Main.js
1 2 3 4 5 |
var input1 = document.getElementById("from"); var autocomplete1 = new google.maps.places.Autocomplete(input1); var input2 = document.getElementById("to"); var autocomplete2 = new google.maps.places.Autocomplete(input2); |
As you can see we are using the Google Places API
Autocomplete API and attaching it to both the input
fields. Now if you open the application and try to type you will get the suggestions
of locations.
Displaying the Google Map
Now we will be displaying the google map
once you load the web application. For this you need to add the below javascript code
Main.js
1 2 3 4 5 6 7 8 9 10 11 |
//javascript.js //set map options var myLatLng = { lat: 38.346, lng: -0.4907 }; var mapOptions = { center: myLatLng, zoom: 7, mapTypeId: google.maps.MapTypeId.ROADMAP, }; //create map var map = new google.maps.Map(document.getElementById("googleMap"), mapOptions); |
As you can see we are providing the Latitude
and Longitude
inside an object. And then we are providing the mapOptions
object in which we are providing the center
and zoom
level of the map. And then we are also providing the mapTypeId
of the map. And then we are using the Google Maps
API to display the map alongside with the options.
Calculating Distance & Time
Now we will be writing the calcRoute()
function which will be executing once we hit the calculate button after entering the locations.
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 |
//create a DirectionsService object to use the route method and get a result for our request var directionsService = new google.maps.DirectionsService(); //create a DirectionsRenderer object which we will use to display the route var directionsDisplay = new google.maps.DirectionsRenderer(); //bind the DirectionsRenderer to the map directionsDisplay.setMap(map); //define calcRoute function function calcRoute() { //create request var request = { origin: document.getElementById("from").value, destination: document.getElementById("to").value, travelMode: google.maps.TravelMode.DRIVING, //WALKING, BYCYCLING, TRANSIT unitSystem: google.maps.UnitSystem.IMPERIAL, }; //pass the request to the route method directionsService.route(request, function (result, status) { if (status == google.maps.DirectionsStatus.OK) { //Get distance and time const output = document.querySelector("#output"); output.innerHTML = "<div class='alert-info'>From: " + document.getElementById("from").value + ".<br />To: " + document.getElementById("to").value + ".<br /> Driving distance <i class='fas fa-road'></i> : " + result.routes[0].legs[0].distance.text + ".<br />Duration <i class='fas fa-hourglass-start'></i> : " + result.routes[0].legs[0].duration.text + ".</div>"; //display route directionsDisplay.setDirections(result); } else { //delete route from map directionsDisplay.setDirections({ routes: [] }); //center map in London map.setCenter(myLatLng); //show error message output.innerHTML = "<div class='alert-danger'><i class='fas fa-exclamation-triangle'></i> Could not retrieve driving distance.</div>"; } }); } |
As you can see we are initializing the directions
api to calculate the routes and then we are passing the locations
entered by the user and then calling the distance matrix api
to calculate the distance
and time
between two locations and then displaying it. And also displaying the directions and routes inside the google map as shown below