JSFiddle - React, Tailwind, and code Playground

by Vadim Gremyachev

HTML

<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="floating-panel">
        <b>Start: </b>
        <span id="start">Current Location</span>
        <b>End: </b>
        <input id="end" type="text" ></input>
        <input id="startInner" type="hidden"></input>
        <button id="btnCalc">Print route</button>
</div>
<div id="map"></div>

CSS

html, body {
    height: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
}

#map {
    height: 100%;
}

#floating-panel {
    position: absolute;
    top: 10px;
    left: 25%;
    z-index: 5;
    background-color: #fff;
    padding: 5px;
    border: 1px solid #999;
    text-align: center;
    font-family: 'Roboto','sans-serif';
    line-height: 30px;
    padding-left: 10px;
}

JavaScript

function initMap() {
    var directionsService = new google.maps.DirectionsService;
    var directionsDisplay = new google.maps.DirectionsRenderer;
    var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 7,
        center: { lat: 41.85, lng: -87.65 }
    });
    directionsDisplay.setMap(map);

    var printRoute = function () {
        calculateAndDisplayRoute(directionsService, directionsDisplay);
    };

    getCurrentLocation(function (loc) {
        if (loc != null) {
            document.getElementById('startInner').value = loc.toString();
            document.getElementById('start').innerHTML = 'Current location';
            map.setCenter(loc);
        }
        else
            document.getElementById('start').innerHTML = 'Current location not found';
    });

    document.getElementById('btnCalc').addEventListener('click', printRoute);
}

function calculateAndDisplayRoute(directionsService, directionsDisplay) {
    directionsService.route({
        origin: document.getElementById('startInner').value,
        destination: document.getElementById('end').value,
        travelMode: google.maps.TravelMode.DRIVING
    }, function (response, status) {
        if (status === google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
        } else {
            window.alert('Directions request failed due to ' + status);
        }
    });
}


function getCurrentLocation(complete) {  
    // Try W3C Geolocation (Preferred)
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function (position) {
            var location = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
            complete(location);
        }, function () {
            complete(null);
        });
    }
    else {
        complete(null);
    }
}

initMap();