JSFiddle - React, Tailwind, and code Playground

by andy

HTML

<div id='map'></div>
<script async defer src='//maps.googleapis.com/maps/api/js?callback=initMap'></script>

CSS

#map{
  width:800px;
  height:600px;
  float:none;
  margin:auto;
}
.gm-bttn{
  padding:1rem;
  color:gold;
  margin:0.25rem;
  border-radius:1rem;
  border:none;
  background:purple;
  transition:ease-in-out all 500ms;
  cursor:pointer;
}
.gm-bttn:hover{
  background:gold;
  color:purple
}

JavaScript

function initMap() {
  let shapes=[];
  let map = new google.maps.Map( document.getElementById("map"), {
    center: { lat: 37.460074, lng: 126.952568 },
    zoom: 16,
  });

  // your original rectangle bounds
  let bounds=new google.maps.LatLngBounds(
    new google.maps.LatLng(20.39623, 77.85009),
    new google.maps.LatLng(24.39623, 80.85009)
  );

  // for convenience, convert bounds to json
  let json=bounds.toJSON();
  let delta={
    long:Math.abs( json.west - json.east ),
    lat:Math.abs( json.north - json.south )
  };

  // create your original rectangle.
  shapes.push(
    new google.maps.Rectangle({
      strokeColor: "#FF0000",
      strokeOpacity: 0.8,
      strokeWeight: 2,
      fillColor: "#FF0000",
      fillOpacity: 0.1,
      map,
      geodesic:true,
      bounds:bounds
    })
  );

  // A ring around the globe of rectangles...
  let max=360 / Math.abs( delta.long );

  for( let i=1; i < max; i++ ){
    // modify json based upon delta values for lat/lng
    json.east -= delta.long,
      json.west -= delta.long;

    // and then add a new rectangle
    shapes.push(
      new google.maps.Rectangle({
        strokeColor: "#FF0000",
        strokeOpacity: 0.8,
        strokeWeight: 2,
        fillColor: "#FF0000",
        fillOpacity: 0.1,
        map,
        geodesic:true,
        bounds:json
      })
    );
  }


  let infoWindow = new google.maps.InfoWindow();

  let clear=document.createElement('button');
  clear.textContent='Remove rectangles'
  clear.className='gm-bttn';
  clear.addEventListener('click',( e )=>shapes.forEach( n=>n.setMap( null ) ) );

  let bttn = document.createElement('button');
  bttn.textContent='Pan to Current Location';
  bttn.className='gm-bttn';

  bttn.addEventListener("click", (e)=>{
    const errorhandler=()=>{
      infoWindow.setPosition( map.getCenter() );
      infoWindow.setContent( navigator.geolocation ? 'Error: The Geolocation service failed.' : 'Error: Your browser doesn\'t support geolocation.' );
  ...