Maps API v3 Directions Waypoints

Directions service with waypoints and custom markers, draggable.

by Ismail Ibraheem Shurrab

HTML

<script src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<div id="map-canvas"></div>

CSS

#map-canvas {
  height: 400px;
}

JavaScript

var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var stop;
var markers = [];

var waypts = [];

stop = new google.maps.LatLng(51.946545, 6.459612)
waypts.push({
  location: stop,
  stopover: true
});
stop = new google.maps.LatLng(51.948621, 6.455030)
waypts.push({
  location: stop,
  stopover: true
});

function initialize() {
  directionsDisplay = new google.maps.DirectionsRenderer({
    suppressMarkers: true
  });

  var myOptions = {
    zoom: 3,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
  }

  map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
  directionsDisplay.setMap(map);
  calcRoute();
}

function calcRoute() {

  for (var i = 0; i < markers.length; i++) {
    markers[i].setMap(null);
  }

  start = new google.maps.LatLng(51.943382, 6.463116);
  end = new google.maps.LatLng(51.947358, 6.443036);

  createMarker(start, 'start', false);
  createMarker(end, 'end', false);

  var request = {
    origin: start,
    destination: end,
    waypoints: waypts,
    optimizeWaypoints: true,
    travelMode: google.maps.DirectionsTravelMode.WALKING
  };

  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
      var route = response.routes[0];

      for (var i = 1; i < route['legs'].length; i++) {

        console.log(route['legs'][i].start_location.toString(), waypts[i - 1].location.toString());

        waypts[i - 1].location = route['legs'][i].start_location
      }

      for (var i = 0; i < waypts.length; i++) {

        createMarker(waypts[i].location, i, true);
      }
    }
  });
}

function createMarker(latlng, posRef, draggable) {

  var marker = new google.maps.Marker({
    position: latlng,
    map: map,
    draggable: draggable,
    posRef: posRef
  });

  markers.push(marker);

  google.maps.event.addListener(marker, 'dragend', function() {

   ...