Google maps saving draggable directions

I’m going to assume that the following is all true:

var map = new google.maps.Map(document.getElementById('map_canvas'), {
        zoom: 8,
        center: new google.maps.LatLng(/* center of map */),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }),
    directions = new google.maps.DirectionsService(),
    displayer = new google.maps.DirectionsRenderer({
        draggable: true
    });

displayer.setMap(map);
directions.route({
    origin: new google.maps.LatLng(/* start point */),
    destination: new google.maps.LatLng(/* end point */),
    travelMode: google.maps.DirectionsTravelMode.DRIVING
}, function (result) {
    displayer.setDirections(result);
});

Basically, this just assumes that the start- and end-points have already been chosen and the default route has already been drawn. (NOTE: The DirectionsRenderer has been initialized with draggable: true.)

When the user changes the route, the application fires a directions_changed event. We can track that like so:

google.maps.event.addListener(displayer, 'directions_changed', some_method);

Something else also happens when the change the route: a new waypoint is created. Here’s how we get at all the waypoints:

var some_method = function () {
    var waypoints = displayer.directions.route[0].legs[0].via_waypoint;
};

The variable waypoints is an array of objects describing the stops the route makes on its way to the destination. (Note that more assumptions have been made: you’re using route[0], legs[0], etc.)

Each waypoint object has a location property, which contains the latitude and longitude (available in location.wa and location.ya respectively, for some reason). So we can tell the application, every time the user changes the route, to rotate through (and store) all the lats and longs of the current waypoints. Once you have those, you can decide how you want to store them (AJAX to a server-side page that stores them in a database, localStorage, etc.)

Then!

The next time you load this page, you can grab those waypoints from the storage and initialize the route like so:

directions.route({
    origin: new google.maps.LatLng(/* start point */),
    destination: new google.maps.LatLng(/* end point */),
    travelMode: google.maps.DirectionsTravelMode.DRIVING,
    waypoints: [
        { location: new google.maps.LatLng(/* lat/lng go here */) } // repeat this as necessary
    ]
}, function (result) {
    displayer.setDirections(result);
});

This should maintain the new route that the user chose. One final note: I left a lot out of this answer, like how they save it, how you know which user wants which route, etc. But the foundation is there. Godspeed.

Leave a Comment