Search code examples
google-maps-api-3map-directions

Handling multiple routes with waypoints in Google Maps v3


I want to display multiple directions with dragable waypoints and save each waypoints associating with origin, destination in object or database whenever Route.prototype.setWayPoints() is called.

This guy is doing that with single route with dragable waypoints (and saving them in database) .

http://vikku.info/programming/google-maps-v3/draggable-directions/saving-draggable-directions-saving-waypoints-google-directions-google-maps-v3.htm

I want multiple routes not one. I googled a lot but couldn't find anything!

Here's what I tried.


function Route(origin, destination){
    this.origin = origin; // LatLng
    this.destination = destination; //LatLng
    this.way_points = null;
};

Route.prototype.drawRoute = function(){
                 this.dser.route({'origin': this.origin,
                   'destination': this.destination,
                   'waypoints': this.way_points,
                   'travelMode': google.maps.DirectionsTravelMode.DRIVING},
                   function(res,sts) {
                          if(sts=='OK'){
                              var dren = new google.maps.DirectionsRenderer({ 'draggable':true }); 
                              dren.setMap(map); //global variable 'map'
                              dren.setDirections(res);
                          }   
                  });
};

Route.prototype.setGMap = function(map){
      this.dren.setMap(map);
};

Route.prototype.setWayPoints = function(){
  this.way_points =   //... what should I do?
};


/* --- main part --- */

r0 = new Route(new google.maps.LatLng( 30, 31 ), new google.maps.LatLng( 40, 41 ));
r0.drawRoute();

// User drags and drops the route on the browser

r0.setWayPoints(); // newly added waypoints should be stored in r0.way_points

r1 = new Route(new google.maps.LatLng( 50, 51 ), new google.maps.LatLng( 60, 61));
r1.drawRoute();

// User drags and drops the route on the browser

r1.setWayPoints(); // newly added waypoints should be stored in r1.way_points

Could anyone tell me how to implement Route.prototype.setWayPoints so that the waypoints in the route on current googlemap can be stored in Route object?


Solution

  • I have changed the approach slightly and added a getPoints-method to the Route-object.

    This method will return an array that consists of origin, waypoints and destination, so you may easy pass it somewhere. (each item of the array will be an array [lat,lng])

    http://jsfiddle.net/doktormolle/fjUqK/