Directions Service

by Lawrence Ross

HTML

<!DOCTYPE html>
<html>
  <head>
    <title>Directions Service</title>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
    <script
      src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCb1xprYSpXd0q_yDsJ1W2UGhfl9_YGKU0&callback=initMap&libraries=&v=weekly"
      defer
    ></script>
    <!-- jsFiddle will insert css and js -->
  </head>
  <body>
    <div id="map"></div>
  </body>
</html>

CSS

/* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
#map {
  height: 100%;
}

/* Optional: Makes the sample page fill the window. */
html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

JavaScript

function initMap() {
    const directionsService = new google.maps.DirectionsService();
    const directionsRenderer = new google.maps.DirectionsRenderer({suppressMarkers: true, polylineOptions:{strokeColor:"#00FF00", strokeWeight:4}});
    const map = new google.maps.Map(document.getElementById("map"), {
      zoom: 7,
      center: {lat: 52.896874,lng:-1.431861},
      
    });
    
    directionsRenderer.setMap(map);
  
calculateAndDisplayRoute(directionsService, directionsRenderer, "52.535614, -7.285257", "52.571321, -1.585436")

}

  function calculateAndDisplayRoute(directionsService, directionsRenderer, p1, p2) {
    directionsService.route(
      {
        origin: {
          query: p1,
        },
        destination: {
          query: p2,
        },
        travelMode: google.maps.TravelMode.DRIVING
      },
      (response, status) => {
        if (status === "OK") {
          directionsRenderer.setDirections(response);
        } else {
          window.alert("Directions request failed due to " + status);
        }
      }
    );
}