In the process of getting distance between two distance co-ordinates, you may find distance by using geometry and algebra. But that's not enough. We may need to find actual travel distance between two points.
This is required when you are building travel or courier website, where actual distance is required rather than straith line distance.
In this article, we will use Google Maps Javascript API and get travel distance between points. So let's start it.
First of all, in the below Javascript code initMap()
function initialize the Google Maps. In the staring, we can set map options in constant center
and options
. and adding markers of two points. point1
and point2
are the points that we will calculate distance between them.
<!DOCTYPE html>
<html>
<head>
<style>
#map {
height: 400px;
width: 600px;
}
</style>
</head>
<body>
<!-- The div elements for the map and message -->
<div id="map"></div>
<div id="msg"></div>
<script>
// Initialize and add the map
var map;
function initMap() {
// The map, centered on Central Park
const center = {lat: 29.7688502, lng: -95.3212729};
const options = {zoom: 15, scaleControl: true, center: center};
map = new google.maps.Map(
document.getElementById('map'), options);
// Locations of landmarks
const point1 = {lat: 29.7678195, lng: -95.3234853};
const point2 = {lat: 29.770591, lng: -95.3152825};
// The markers for The point1 and The point2 Collection
var mk1 = new google.maps.Marker({position: point1, map: map});
var mk2 = new google.maps.Marker({position: point2, map: map});
}
</script>
<!-- replace api key below -->
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=GOOGLE_API_KEY&callback=initMap">
</script>
</body>
</html>
In the initMap()
function add the line to draw strait line between two points.
var line = new google.maps.Polyline({path: [point1, point2], map: map});
We will need Haversine formula to calculate strait line distance between these points, add the below function before the initMap() function to calculate distance between these points. The function accepts two parameters of points which we want to calculate distance between them.
function haversineDistance(mk1, mk2) {
var rad = 6371.0710; // Radius of the Earth in kms
var rlat1 = mk1.position.lat() * (Math.PI/180); // Convert degrees to radians
var rlat2 = mk2.position.lat() * (Math.PI/180); // Convert degrees to radians
var difflat = rlat2-rlat1; // Radian difference (latitudes)
var difflon = (mk2.position.lng()-mk1.position.lng()) * (Math.PI/180); // Radian difference (longitudes)
var d = 2 * rad * Math.asin(Math.sqrt(Math.sin(difflat/2)*Math.sin(difflat/2)+Math.cos(rlat1)*Math.cos(rlat2)*Math.sin(difflon/2)*Math.sin(difflon/2)));
return d;
}
Now we call method to get distance and print.
var distance = haversineDistance(mk1, mk2);
document.getElementById('msg').innerHTML = "Distance between markers: " + distance.toFixed(2) + " Kms.";
We will need the travel distance between two co-ordinates, because straight line distance is not proper way to calculate distance. For that we will use Google Maps Directions API.
We have alredy initialized Google Maps, so just add the below code in initMap() function.
let directionsService = new google.maps.DirectionsService();
let directionsRenderer = new google.maps.DirectionsRenderer();
directionsRenderer.setMap(map); // Existing map object displays directions
// Create route from existing points used for markers
const route = {
origin: point1,
destination: point2,
travelMode: 'DRIVING'
}
directionsService.route(route,
// capture directions
function(response, status) {
if (status !== 'OK') {
window.alert('Directions request failed due to ' + status);
return;
} else {
directionsRenderer.setDirections(response); // Add route to the map
var directionsData = response.routes[0].legs[0]; // Get data about the mapped route
if (!directionsData) {
window.alert('Directions request failed');
return;
} else {
document.getElementById('msg').innerHTML += " Travel distance is " + directionsData.distance.text + " (" + directionsData.duration.text + ").";
}
}
});
This will render travel distance between two points.
directionsService.route function variable returns Json format.
"routes": [{
"legs": [{
"distance": {
"text": "1.1 km",
value: 1100
},
{
"duration": {
"text": "3 mins",
value: 172
}
}
}]
}]
This way you can get travel distance between points using Google Maps Javascript API. Please let us know in the below comment section if you have any query.
Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]
How to Preview an Image Before it is Uploaded Using jQuery
Use the JS readAsDataURL() Method You...How to configure NFS on Linux
NFS or Network File System is used to sh...Angular 9 - CRUD Example with PHP and MySql
In this tutorial, you'll learn to en...Unable to acquire the dpkg frontend lock (/var/lib/dpkg/lock-frontend), is another process using it?
Sometimes when you are working apt-get c...How To Install the Django Web Framework on Ubuntu
Django is one of the best and very popul...