Search code examples
jquerygoogle-mapsgoogle-maps-api-3gmaps.js

gmaps: how to add multiple destinations


I'm using gmaps with JQuery. I want to display the directions from point A to point B, and then to point C, in a map. I'm using this code, but it's not working:

<script type="text/javascript">
    var map;
    $(document).ready(function(){
        map = new GMaps({
            div: '#map',
            lat: -12.043333,
            lng: -77.028333
        });
        map.drawRoute({
            origin: [-12.044012922866312, -77.02470665341184],
            destination: [-12.090814532191756, -77.02271108990476],
            destination: [-12.044012922866312, -77.02470665341184],
            travelMode: 'driving',
            strokeColor: '#131540',
            strokeOpacity: 0.6,
            strokeWeight: 6
        });
    });
</script>

Solution

  • The object literal you're passing into the map.drawRoute() function has the destination property repeated twice. A JavaScript object can only have one property with the same name, so the second destination overwrites the first.

    The documentation for .drawRoute() indicates that you should use a waypoints array for intermediate waypoints. While I haven't tested it, I suspect that the code you want would look something like this:

            map.drawRoute({
                origin: [-12.044012922866312, -77.02470665341184],
                waypoints: [
                    {
                        location: new google.maps.LatLng(
                            -12.090814532191756,
                            -77.02271108990476
                        ),
                        stopover: true
                    }
                ],
                destination: [-12.044012922866312, -77.02470665341184],
                travelMode: 'driving',
                strokeColor: '#131540',
                strokeOpacity: 0.6,
                strokeWeight: 6
            });