How to Display Multiple Google Maps Per Page with API V3

How to Display Multiple Google Maps per page with API V3

Here is how I have been able to generate multiple maps on the same page using Google Map API V3. Kindly note that this is an off the cuff code that addresses the issue above.

The HTML bit

<div id="map_canvas" style="width:700px; height:500px; margin-left:80px;"></div>
<div id="map_canvas2" style="width:700px; height:500px; margin-left:80px;"></div>

Javascript for map initialization

<script type="text/javascript">
var map, map2;

function initialize(condition) {
// create the maps
var myOptions = {
zoom: 14,
center: new google.maps.LatLng(0.0, 0.0),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

map2 = new google.maps.Map(document.getElementById("map_canvas2"), myOptions);
}
</script>

Google Maps API v3 - using multiple maps on page, each with one infowindow, on click only the last map displays popup

Your loop is changing the value of currentMap and currentMarker (they are x when you assign the listener, but y when the listener actually executes). Try closing around the values you want e.g.:

(function(currentMarker, currentMap) {
currentMarker.addListener('click', function() {
popupBox.open(currentMap, currentMarker);
});
})(currentMarker, currentMap);

Two Google Maps on same page with markers

You are including the API twice. That generates the warning:

You have included the Google Maps API multiple times on this page. This may cause unexpected errors

Only include the API one time, put the initialization code for both maps inside a single initialization function.

One option:

<script>
function initialize() {
initMap();
initMap2();
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initialize">
</script>

proof of concept fiddle

image of resulting map

code snippet:

var markers = [{  GPS1: -34.031342,  GPS2: 18.577419,  client_address: "somewhere1"}];
function initialize() { initMap(); initMap2();}
function initMap() { var latlng = new google.maps.LatLng(-34.031342, 18.577419); // default location var myOptions = { zoom: 16, center: latlng, mapTypeId: google.maps.MapTypeId.SATELLITE, mapTypeControl: true };
var map = new google.maps.Map(document.getElementById('mapall'), myOptions); var infowindow = new google.maps.InfoWindow(), marker, lat, lng;
for (i = 0; i < markers.length; i++) { lat = (markers[i].GPS1); lng = (markers[i].GPS2); name = (markers[i].client_address);
marker = new google.maps.Marker({ position: new google.maps.LatLng(lat, lng), name: name, map: map }); google.maps.event.addListener(marker, 'click', function(e) { infowindow.setContent(this.name); infowindow.open(map, this); }.bind(marker)); }}var markers2 = [{ GPS1: -33.92465, GPS2: 18.84382, client_address: "somewhere2"}];
function initMap2() { var latlng = new google.maps.LatLng(-33.92465, 18.84382); // default location var myOptions = { zoom: 16, center: latlng, mapTypeId: google.maps.MapTypeId.SATELLITE, mapTypeControl: true };
var map = new google.maps.Map(document.getElementById('mapall2'), myOptions); var infowindow = new google.maps.InfoWindow(), marker, lat, lng;
for (i = 0; i < markers2.length; i++) { lat = (markers2[i].GPS1); lng = (markers2[i].GPS2); name = (markers2[i].client_address);
marker = new google.maps.Marker({ position: new google.maps.LatLng(lat, lng), name: name, map: map }); google.maps.event.addListener(marker, 'click', function(e) { infowindow.setContent(this.name); infowindow.open(map, this); }.bind(marker)); }}
html,body {  height: 100%;  width: 100%;  margin: 0px;  padding: 0px}
#mapall,#mapall2 { height: 50%; width: 100%; border: red solid 1px;}
<div id="mapall"></div><div id="mapall2"></div><script async defer src="https://maps.googleapis.com/maps/api/js?callback=initialize"></script>

Can you display multiple maps on the same page with directions using Google Maps JavaScript API v3?

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); }
});
}

Google Maps JS API v3 - Simple Multiple Marker Example

This is the simplest I could reduce it to:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Google Maps Multiple Markers</title>
<script src="http://maps.google.com/maps/api/js?key=YOUR_API_KEY"
type="text/javascript"></script>
</head>
<body>
<div id="map" style="width: 500px; height: 400px;"></div>

<script type="text/javascript">
var locations = [
['Bondi Beach', -33.890542, 151.274856, 4],
['Coogee Beach', -33.923036, 151.259052, 5],
['Cronulla Beach', -34.028249, 151.157507, 3],
['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
['Maroubra Beach', -33.950198, 151.259302, 1]
];

var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(-33.92, 151.25),
mapTypeId: google.maps.MapTypeId.ROADMAP
});

var infowindow = new google.maps.InfoWindow();

var marker, i;

for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});

google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
</script>
</body>
</html>

‍ Edit/fork on a Codepen →

SCREENSHOT

Google Maps Multiple Markers

There is some closure magic happening when passing the callback argument to the addListener method. This can be quite a tricky topic if you are not familiar with how closures work. I would suggest checking out the following Mozilla article for a brief introduction if it is the case:

❯ Mozilla Dev Center: Working with Closures

Displaying Multiple Google Maps on one page

Possible duplicate of Multiple Google Maps won't display on single page

You have a function with the same name in both the javascript files ("initialize").

That won't work.



Related Topics



Leave a reply



Submit