JSFiddle - React, Tailwind, and code Playground
HTML
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<div id="distance">My distance</div>
<div id="map_canvas"></div>
CSS
html, body, #map_canvas { margin: 0; padding: 0; height: 100% }
JavaScript
var location1 = new google.maps.LatLng(42.3584308, -71.0597732);
var location2 = new google.maps.LatLng(42.348805455204214, -71.07485794349975);
var map;
var mapOptions = { center: new google.maps.LatLng(0.0, 0.0), zoom: 2,
mapTypeId: google.maps.MapTypeId.ROADMAP };
function initialize() {
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer(
{
suppressMarkers: true,
suppressInfoWindows: true
});
directionsDisplay.setMap(map);
var request = {
origin: location1,
destination:location2,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status)
{
if (status == google.maps.DirectionsStatus.OK)
{
directionsDisplay.setDirections(response);
//alert("the distance: " + response.routes[0].legs[0].distance.text);
distance = "The distance between the two points on the chosen route is: "+response.routes[0].legs[0].distance.text;
//distance += "<br/>The aproximative driving time is: "+response.routes[0].legs[0].duration.text;
document.getElementById("distance").innerHTML = distance;
}
});
// show a line between the two points
var line = new google.maps.Polyline({
map: map,
path: [location1, location2],
strokeWeight: 7,
strokeOpacity: 0.8,
strokeColor: "#FFAA00"
});
}
google.maps.event.addDomListener(window, 'load', initialize);