JSFiddle - React, Tailwind, and code Playground

by andy

HTML

<div id="map"></div>
<button type='button' data-colour='yellow'>Yellow Off</button>
<button type='button' data-colour='red'>Red Off</button>

<script defer async src="//maps.google.com/maps/api/js?logged_in=false&callback=initialize"></script>

CSS

#map {
  width: 100%;
  height: 90vh
}

JavaScript

function initialize() {
			  const polygons = {};
			  const myLatLng = new google.maps.LatLng(55.73, -6.25);
			  const myOptions = {
			    zoom: 10,
			    center: myLatLng,
			    mapTypeId: google.maps.MapTypeId.HYBRID
			  };
			  const map = new google.maps.Map(document.getElementById('map'), myOptions);

			  let yellowCoords = [{
			    lat: 55.828897,
			    lng: -6.398249
			  }, {
			    lat: 55.835067,
			    lng: -6.126337
			  }, {
			    lat: 55.674712,
			    lng: -6.305552
			  }];
			  let yellowPolygon = new google.maps.Polygon({
			    paths: yellowCoords,
			    strokeColor: 'yellow',
			    strokeOpacity: .7,
			    strokeWeight: 2,
			    fillColor: 'yellow',
			    fillOpacity: 0.2
			  });
			  yellowPolygon.setMap(map);

			  let redCoords = [{
			    lat: 55.668897,
			    lng: -6.198249
			  }, {
			    lat: 55.835067,
			    lng: -6.026337
			  }, {
			    lat: 55.674712,
			    lng: -6.005552
			  }];
			  let redPolygon = new google.maps.Polygon({
			    paths: redCoords,
			    strokeColor: 'red',
			    strokeOpacity: .7,
			    strokeWeight: 2,
			    fillColor: 'red',
			    fillOpacity: 0.2
			  });
			  redPolygon.setMap(map);

			  polygons.yellow = yellowPolygon;
			  polygons.red = redPolygon;

			  const clickhandler = (e) => {
			    let poly = polygons[e.target.dataset.colour]
			    poly.setMap(poly.getMap() ? null : map)
			  }

			  document.querySelectorAll('button[type="button"][data-colour]').forEach(bttn => bttn.addEventListener('click', clickhandler))
			}