JSFiddle - React, Tailwind, and code Playground

by Lawrence Ross

HTML

<script src="https://maps.googleapis.com/maps/api/js?sensor=false&amp;libraries=geometry,places&amp;key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="distance"></div>
<div id="map_canvas" style="border: 2px solid #3872ac;"></div>

CSS

html, body, #map_canvas {
    height: 100%;
    width: 100%;
    margin: 0px;
    padding: 0px
}

JavaScript

var geocoder;
var map;
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();

function initialize() {
    var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
        center: new google.maps.LatLng(37.4419, -122.1419),
        zoom: 13,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });
    var directionsService = new google.maps.DirectionsService();
    directionsDisplay.setMap(map);
    calcRoute("New York, NY", "Baltimore, MD");
}
google.maps.event.addDomListener(window, "load", initialize);

function calcRoute(ref1, ref2) {
    var start = String(ref1);
    var end = String(ref2);
    var args = {
        origin: start,
        destination: end,
        travelMode: google.maps.TravelMode.DRIVING
    }
    directionsService.route(args, function (response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
            var myroute = directionsDisplay.directions.routes[0];
            var distance = 0;
            for (i = 0; i < myroute.legs.length; i++) {
                distance += myroute.legs[i].distance.value;
                //for each 'leg'(route between two waypoints) we get the distance and add it to the total
            }
            document.getElementById('distance').innerHTML = distance +" meters";
        } else {
            alert("fail");
        }
    });

};