JSFiddle - React, Tailwind, and code Playground
HTML
<div class="map" data-zoom="1" data-lat="1" data-lng="1"></div>
<div class="map" data-zoom="3" data-lat="10" data-lng="10"></div>
<div class="map" data-zoom="5" data-lat="-10" data-lng="10"></div>
<div class="map" data-zoom="2" data-lat="20" data-lng="-20"></div>
<div class="map" data-zoom="4" data-lat="33" data-lng="-33"></div>
CSS
.map{cursor:pointer}
.map, .mapped {
display:inline-block;
background:silver;margin:4px;
}
.mapped {
width:200px;
height:200px;
}
.map:after {
content:'click here to create a map';
}
JavaScript
//create maps of elements with className map
document.addEventListener('click', function (e) {
var node = e.target,
callback, script, execCallbacks;
//check the class
if (node.className === 'map') {
//assign a new class to prevent from further clicks
node.className = 'mapped';
//when window.google isn't available, create it
if (!window.google) {
window.google = {};
}
//we will store the callbacks in an array
if (!window.google.callbacks) {
window.google.callbacks = [];
}
//function that executes the callbacks
if (!window.google.execCallbacks) {
window.google.execCallbacks = function () {
while (this.callbacks.length) {
this.callbacks.shift()();
}
};
}
//define the callback(creates a simple map)
callback = function () {
new google.maps.Map(node, {
zoom: 1 * node.getAttribute('data-zoom'),
center: new google.maps.LatLng(node.getAttribute('data-lat'),
node.getAttribute('data-lng'))
});
};
//google.maps isn't loaded yet
if (!window.google.maps) {
//push the callback to the callbacks
window.google.callbacks.push(callback);
//load the API
script = document.createElement('script');
script.src = "https://maps.googleapis.com/maps/api/js?v=3&" +
"callback=google.execCallbacks";
document.getElementsByTagName('script')[0].parentNode.appendChild(script);
}
//API is already loaded, run the callback directly
else {
callback();
}
}
});