Google Maps draggable directions

by Arjan Haverkamp

HTML

<script src="http://maps.google.com/maps/api/js?sensor=false&amp;.js"></script>
<div id="directionsPanel"></div>
<div id="map"></div>

CSS

#map{
    width: 450px;
    height: 400px;
}
#directionsPanel {
  width: 200px;
  float: left;
}

JavaScript

let map, custom

const myOptions = {
    zoom: 6,
    center: new google.maps.LatLng(52.87916, 18.32910),
    mapTypeId: 'terrain'
};
const markers = [];

window.onload = () => {
  map = new google.maps.Map(document.querySelector('#map'), myOptions);
  custom = new CustomDirectionsRenderer(new google.maps.LatLng(50.87916, 16.32910), new google.maps.LatLng(52.87916, 16.32910), map);
    
    //you have access to marker :)
    custom.startMarker.setTitle('POLAND!!');
}

class CustomDirectionsRenderer extends google.maps.MVCObject {
  /**
   * @param {google.maps.LatLng|google.maps.LatLngLiteral} startPoint
   * @param {google.maps.LatLng|google.maps.LatLngLiteral} endPoint
   * @param {google.maps.Map} map
   */
  constructor(startPoint, endPoint, map) {
    super();

    this.map = map;

    this.directionsDisplay = new google.maps.DirectionsRenderer({
      draggable: true,
      suppressMarkers: true,
      map,
    });

    this.directionsService = new google.maps.DirectionsService();

    this.draggedMarker = null;
    this.waypointsMarkers = [];

    this.polyline = "";
    this.polylinePoints = [];

    this.startMarker = new google.maps.Marker({
      position: startPoint,
      title: "Start",
      map,
      draggable: true,
      optimized: false,
    });

    this.endMarker = new google.maps.Marker({
      position: endPoint,
      title: "End",
      map,
      draggable: true,
      optimized: false,
    });

    // DirectionsRenderer change -> check waypoint marker count
    this.directionsDisplay.addListener("directions_changed", () => {
      this.checkWaypoints();
    });

    // Marker drag handlers
    const attachDragHandlers = (marker) => {
      marker.addListener("dragstart", () => this.onDragStart(marker));
      marker.addListener("drag", () => this.onDrag(marker));
      marker.addListener("dragend", () => this.onDragEnd(marker));
    };

   ...