<div id="map" style="height: 550px; width: 550px;"></div>
function initMap() {
  // https://developers.google.com/maps/documentation/javascript/adding-a-google-map
  
  // custom icons
  const iconBase = 'https://s7d2.scene7.com/is/image/PartyRental/';
  const iconTruck = iconBase + 'hippoTruck?hei=50&fmt=png-alpha';
  const iconDest = iconBase + 'pin?hei=30&fmt=png-alpha';
  
  // establish coordinates
  const truckLocation = new google.maps.LatLng(40.866840, -74.053627);
  const destination = new google.maps.LatLng(40.748440, -73.985664); 
  
  // create the map!
  const map = new google.maps.Map(
    document.getElementById('map'),
    { zoom: 15, center: destination },
  )
    
  // add pins
  const destinationMarker = new google.maps.Marker({
    position: destination,
    icon: iconDest,
    map,
  });
  const truckMarker = new google.maps.Marker({
    position: truckLocation,
    icon: iconTruck,
    map,
  });
  
  // extend the bounds of the map to where both pins sit
  const bounds = new google.maps.LatLngBounds();  
  bounds.extend(destination);
  bounds.extend(truckLocation);
  map.fitBounds(bounds, 50);
  map.panToBounds(bounds);
  
  /**
   * If Point A and Point B are too close, sometimes the map appears broken.
   * The listener below checks to see if the zoom is TOO close, and zooms back out.
   */
  // const listener = google.maps.event.addListenerOnce(map, "idle", function() {
  //   if (map.getZoom() > 15) map.setZoom(15); 
  // })
  
  // map the route!
  const directionsService = new google.maps.DirectionsService();
  const directionsRenderer = new google.maps.DirectionsRenderer();
  const directionRequest = {
    origin: truckLocation,
    destination: destination,
    travelMode: 'DRIVING',
  };
  directionsService.route(directionRequest, function(result, status) {
    if (status == 'OK') {
      directionsRenderer.setOptions({ 
        map,
        suppressMarkers: true,
        preserveViewport: true,
      })
      directionsRenderer.setDirections(result);
    }
  });
}
Run Pen

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.