Google map - Multiple Markers and InfoWindows/Popups & CMS items

Hey there,

I am going throught this problem now, and on this discussion:
https://discourse.webflow.com/t/can-i-use-multiple-map-locations-with-cms
with the help of @Brando and @zbrah in the last comment ([Feb '18]) I’he come up with this solution:

1 - create or import your own collection with, at least, a latitude and longitude field



2 - Create a section or a div an give it an ID map
3 - Inside that div put an embed element, a collection list and another embed element
Captura de ecrã 2020-04-10, às 21.07.23
4 - In the embed element, before the collection list, we declare a variable that will store all markers positions in your cms collection

5 - in each collection item, insert another embed element and save there locations:
Captura de ecrã 2020-04-12, às 10.57.34

6 - Finally, in embed element after the collection list, we generate the map and put all the markers inside locations array. This way the map will only be generated one time.
Here’s my code:

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false&key=YOUR_API_KEY"></script>
<script type="text/javascript">

function init_map(locations, center) {
	var mapStyles=[ YOUR STYLES ]
	var mapOptions = {
		    zoom: 16,
		    scrollwheel: false,
		    center: center,
			styles: mapStyles,
			disableDefaultUI: false          
	};
	var map = new google.maps.Map(document.getElementById("map"), mapOptions);
	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));
            }
    return map;
    }
var center = {lat:YOUR_LAT_CENTER,lng:lat:YOUR_LNG_CENTER};
init_map(locations, center);
</script>

And you are done!

1 Like