Calculate Google Maps distances with different travel modes
Display routes and calculate distance with different travel modes (driving, walking, bicycling, transit) from point A to point B.
by Shiv Singh
HTML
<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<header id="floating-panel"> <b>Mode of Travels: </b>
<select id="mode">
<option value="DRIVING">Driving</option>
<option value="WALKING">Walking</option>
<option value="BICYCLING">Bicycling</option>
<option value="TRANSIT">Transit</option>
</select>
</header>
<section id="map-canvas"></section>
<aside id="output">
<h3>Distance</h3>
<b> A to B: </b><span id="a2b"></span>
</aside>
CSS
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
* {
box-sizing: border-box;
margin: 2px;
}
#map-canvas {
height: 100%;
width: 78%;
float: left;
border: 1px solid #996699;
border-radius: 5px;
}
#floating-panel {
position: float top;
z-index: 5;
background-color: #9999cc;
padding: 5px;
border: 1px solid #996699;
border-radius: 5px;
text-align: center;
font-family: 'Roboto', 'sans-serif';
line-height: 30px;
padding-left: 10px;
}
#output {
float: left;
height: 100%;
}
JavaScript
function initMap() {
var pointA = new google.maps.LatLng(51.2750, 1.0870),
pointB = new google.maps.LatLng(51.5379, 0.7138),
center = new google.maps.LatLng(51.3, 0.8),
myOptions = {
zoom: 8,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP
},
map = new google.maps.Map(document.getElementById('map-canvas'), myOptions),
// Instantiate a directions service.
directionsService = new google.maps.DirectionsService;
directionsDisplay = new google.maps.DirectionsRenderer({
map: map
}),
outputAtoB = document.getElementById('a2b'),
// click on marker B to get route from A to B
calculateAndDisplayRoute(directionsService, directionsDisplay, pointA, pointB, outputAtoB);
var travelMode = document.getElementById("mode");
travelMode.addEventListener("change", function() {
calculateAndDisplayRoute(directionsService, directionsDisplay, pointA, pointB, outputAtoB);
});
}
function calculateAndDisplayRoute(directionsService, directionsDisplay, pointA, pointB, outputTxt) {
var selectedMode = document.getElementById('mode').value;
directionsService.route({
origin: pointA,
destination: pointB,
unitSystem: google.maps.UnitSystem.METRIC,
travelMode: google.maps.TravelMode[selectedMode]
}, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
outputTxt.innerHTML = Math.round(directionsDisplay.getDirections().routes[directionsDisplay.getRouteIndex()].legs[0].distance.value / 1000) + "Km";
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
initMap();