Circles

by Lawrence Ross

HTML

<!DOCTYPE html>
<html>
  <head>
    <title>Circles</title>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
    <!-- jsFiddle will insert css and js -->
  </head>
  <body>
    <input id="btn" type="button" value="computeBounds" />
    <div id="map"></div>

    <!-- Async script executes immediately and must be after any DOM elements used in callback. -->
    <script
      src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg&callback=initMap&libraries=geometry&v=weekly&channel=2"
      async
    ></script>
  </body>
</html>

CSS

/* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
#map {
  height: 90%;
}

/* Optional: Makes the sample page fill the window. */
html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

JavaScript

let map;
function initMap() {
  // Create the map.
  map = new google.maps.Map(document.getElementById("map"), {
    zoom: 4,
    center: { lat: 37.09, lng: -95.712 },
    mapTypeId: "terrain",
  });
  google.maps.event.addListenerOnce(map, 'bounds_changed', function(){
  var bounds = map.getBounds();
  console.log(bounds.toUrlValue(6));
  const circle = new google.maps.Circle({
      strokeColor: "#FF0000",
      strokeOpacity: 0.8,
      strokeWeight: 2,
      fillColor: "#FF0000",
      fillOpacity: 0.35,
      map: map,
      center: bounds.getCenter(),
      radius: getRadius(),
  });
});
google.maps.event.addDomListener(document.getElementById('btn'), 'click', function() {
  var bounds = map.getBounds();
  console.log(bounds.toUrlValue(6));
  const circle = new google.maps.Circle({
      strokeColor: "#0000FF",
      strokeOpacity: 0.8,
      strokeWeight: 2,
      fillColor: "#0000FF",
      fillOpacity: 0.35,
      map: map,
      center: bounds.getCenter(),
      radius: getRadius(),
  });
})
}
const getRadius = function() {
console.log("getRadius")
    const bounds = map.getBounds();
    if (!bounds) return null;
console.log("getRadius bounds="+bounds.toUrlValue(6))
    // computeDistanceBetween returns meters
    const nsRadius = google.maps.geometry.spherical.computeDistanceBetween(
      bounds.getCenter(),
      new google.maps.LatLng(bounds.getNorthEast().lat(), bounds.getCenter().lng())
    );
    const ewRadius = google.maps.geometry.spherical.computeDistanceBetween(
      bounds.getCenter(),
      new google.maps.LatLng(bounds.getCenter().lat(),bounds.getNorthEast().lng())
    );

    const radius = nsRadius <= ewRadius ? nsRadius : ewRadius;
    return Number((radius).toFixed(2));
  }