Skip to content Skip to sidebar Skip to footer

Can You Display Multiple Maps On The Same Page With Directions Using Google Maps JavaScript API V3?

I'm trying to create multiple maps on the same page with different transit directions in each one. I've been able to iteratively create multiple Google maps, but I can't get diffe

Solution 1:

A unique DirectionsRenederer needs to be associated with each map. Note that the DirectionsService is subject to a quota and rate limits, if you have lots of these maps you will have to check the return status and handle OVER_QUERY_LIMIT errors appropriately (you may want to handle errors in general, so the service will tell you why some maps don't show a route).

working example (with 2 maps)

var directionsDisplay = [];
var directionsService = [];
var map = [];
var coordinates;

function initialize(){

    for (var i = 0; i < arrayOfObjects.length; i++){
        directionsService[i] = new google.maps.DirectionsService();

        directionsDisplay[i] = new google.maps.DirectionsRenderer();       

        var latitude = arrayOfObjects[i].latitude;
        var longitude = arrayOfObjects[i].longitude;

        coordinates = new google.maps.LatLng(latitude, longitude);

        var mapOptions = {
            zoom: 15,       
            center: coordinates
        };

        var numString = i.toString();
        var thisMapID = "map-canvas" + numString;

        map[i] = new google.maps.Map(document.getElementById(thisMapID), mapOptions);
        directionsDisplay[i].setMap(map[i]);

        calcRoute(i);
    };
}

var startingLocation = new google.maps.LatLng(40.768211, -73.957721);

function calcRoute(index){
    var request = {
        origin: startingLocation,
        destination: map[index].getCenter(),
        travelMode: google.maps.TravelMode.TRANSIT
    };

    directionsService[index].route(request, function(response, status){
        if(status == google.maps.DirectionsStatus.OK){
            directionsDisplay[index].setDirections(response);          
        } else { alert("Directions request failed: " + status); }
    }); 
}

Post a Comment for "Can You Display Multiple Maps On The Same Page With Directions Using Google Maps JavaScript API V3?"