I’m having trouble with displaying multiple markers on my map. I have an array with location data that includes popup content and addresses, but only one marker appears on the map.
I’m trying to create a map that shows several locations based on my data array. Each marker should have a click event that opens an info popup. However, when I run my code, only the final marker from my array gets displayed on the map.
Here’s my current implementation:
<div class="MapContainer">
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY" type="text/javascript"></script>
<div id="mapDisplay" style="width: 800px; height: 500px;"></div>
<script type="text/javascript">
var places = [
['<h3>Location A</h3>', 'SW1A 1AA'],
['<h3>Location B</h3>', 'M1 1AA']
];
var mapInstance = new google.maps.Map(document.getElementById('mapDisplay'), {
zoom: 6,
center: new google.maps.LatLng(51.5074, -0.1278),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var popup = new google.maps.InfoWindow();
var addressConverter = new google.maps.Geocoder();
var mapMarker = new google.maps.Marker({ map: mapInstance });
var index;
for (index = 0; index < places.length; index++) {
var geoRequest = {address: places[index][1]};
addressConverter.geocode(geoRequest, function(response, status) {
mapMarker.setPosition(response[0].geometry.location);
});
google.maps.event.addListener(mapMarker, 'click', (function(mapMarker, index) {
return function() {
popup.setContent(places[index][0]);
popup.open(mapInstance, mapMarker);
}
})(mapMarker, index));
}
</script>
</div>
Can someone help me figure out why all my markers aren’t showing up? I expected to see multiple pins on the map but I’m only getting one.