0

I'm using Google Maps API to create a direction with the given points.

I need to order the points as 1,2,3...99 (It's done).

Also the points must be draggable.

But when I make the points draggable, the direction does not refresh itself, point's locations change but not the direction,

Here is the sample code(taken from the --> Google Maps Directions using 1-2-3 instead of A-B-C);

<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
  google.load("maps", "3",{other_params:"sensor=false"});

  function init(){
    directionsService = new google.maps.DirectionsService();

    var pos = new google.maps.LatLng(41.218624, -73.748358);
    var myOptions = {
        zoom: 15,
        center: pos,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    map = new google.maps.Map(document.getElementById('map'), myOptions);
    directionsDisplay = new google.maps.DirectionsRenderer({map: map, suppressMarkers: true,draggable:true});

    directionsService.route({
        origin: "New York",
        destination: "Chicago",
        waypoints: [{location:"Philadelphia"}, {location:"Boston"}], //other duration points
        optimizeWaypoints: true,
        travelMode: google.maps.TravelMode.DRIVING
    }, function(response, status) {
        if (status === google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
            var my_route = response.routes[0];
            for (var i = 0; i < my_route.legs.length; i++) {
                var marker = new google.maps.Marker({
                    position: my_route.legs[i].start_location,
                    draggable:true,
                    label: ""+(i+1),
                    map: map
                });
            }
            var marker = new google.maps.Marker({
                position: my_route.legs[i-1].end_location,
                draggable:true,
                label: ""+(i+1),
                map: map
            });
        } else {
            vts.alertDialog( window.localization.error,
                window.localization.error_direction_calculate + ": " + status,
                BootstrapDialog.TYPE_DANGER);
        }
    });

}    
</script>
<body style="margin:0px; padding:0px;" onload="init()">
     <div id="map" style="height:400px; width:500px;"></div>
</body>

Here is the screen shots;

enter image description here

Here is the problem;

enter image description here

The thing is that, I have to do it with both markers and draggable properties.

Thanks in advance

Community
  • 1
  • 1
NewPHPer
  • 238
  • 6
  • 22

1 Answers1

5

Just recalculate the route every time a marker is dragged. Listen for the dragend event and calculate route again and then render it on map, again with suppressing markers. Careful though, if you drag a marker to some position where route cannot be calculated (e.g. over sea, or some mountains, etc.) you would get error when re-calculating the route.

Working example:

function init(){
    var markers = [];
    var directionsService = new google.maps.DirectionsService();
    var pos = new google.maps.LatLng(41.218624, -73.748358);
    var myOptions = {
        zoom: 15,
        center: pos,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    map = new google.maps.Map(document.getElementById('map'), myOptions);
    directionsDisplay = new google.maps.DirectionsRenderer({map: map, suppressMarkers: true});

    directionsService.route({
        origin: "New York",
        destination: "Chicago",
        waypoints: [{location:"Philadelphia"}, {location:"Boston"}], //other duration points
        optimizeWaypoints: true,
        travelMode: google.maps.TravelMode.DRIVING
    }, function(response, status) {
        if (status === google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
   var my_route = response.routes[0];
            for (var i = 0; i < my_route.legs.length; i++) {
                addDraggableDirectionsMarker(my_route.legs[i].start_location, i+1, map, markers, directionsService, directionsDisplay);
            }
   addDraggableDirectionsMarker(my_route.legs[i-1].end_location, i+1, map, markers, directionsService, directionsDisplay);
        } else {
            vts.alertDialog( window.localization.error,
                window.localization.error_direction_calculate + ": " + status,
                BootstrapDialog.TYPE_DANGER);
        }
    });

}    

function addDraggableDirectionsMarker(position, label, map, markers, directionsService, directionsDisplay){
    var marker = new google.maps.Marker({
        position: position,
        label: "" + label,
        map: map,
  draggable: true
    });
    google.maps.event.addListener(marker, 'click', function(){
        //do whatever you want on marker click
    }); 
 google.maps.event.addListener(marker, 'dragend', function(){
  if(markers.length < 2) return;
  var waypoints = [];
  for(var i = 1; i < markers.length - 1; i++) waypoints.push({location:markers[i].getPosition()});
     directionsService.route({
         origin: markers[0].getPosition(),
         destination: markers[markers.length-1].getPosition(),
         waypoints: waypoints,
         optimizeWaypoints: true,
         travelMode: google.maps.TravelMode.DRIVING
     }, function(response, status) {
         if (status === google.maps.DirectionsStatus.OK) {
             directionsDisplay.setDirections(response);
                    //uncomment following code if you want the markers you dragged to snap to the route, closest to the point where you dragged the marker
                    /*var my_route = response.routes[0];
            for (var i = 0; i < my_route.legs.length; i++) {
            markers[i].setPosition(my_route.legs[i].start_location);
            }
            markers[i].setPosition(my_route.legs[i-1].end_location);*/
         } else {
             vts.alertDialog( window.localization.error,
                 window.localization.error_direction_calculate + ": " + status,
                 BootstrapDialog.TYPE_DANGER);
         }
  });
 });
 markers.push(marker);
}
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("maps", "3",{other_params:"sensor=false"});
</script>
<body style="margin:0px; padding:0px;" onload="init()">
  <div id="map" style="height:400px; width:500px;"></div>
</body>
Matej P.
  • 5,303
  • 1
  • 28
  • 44
  • If you drag a marker off a street (in a park or on a building) the route will be recalculated but the marker will stay there which looks a bit odd... – MrUpsidown Jun 15 '16 at 10:08
  • I have edited the code, to contain piece of code which would move dragged markers to the location on route closest to the dragged location (snap them to route). I have left it commented though, as it's not always desired behaviour. But thanks for the feedback. – Matej P. Jun 15 '16 at 10:21