Restrict Map to MaxZoom

by Wolf

HTML

<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCOW7b0eVJzLBlTz1eY9XP04VJ48C_uaMQ&callback=initMap" async defer></script>

CSS

/* Always set the map height explicitly to define the size of the div * element that contains the map. */

#map {
  height: 100%;
}


/* Optional: Makes the sample page fill the window. */

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

JavaScript

var map;
var maxZoomService;

function initMap() {
  maxZoomService = new google.maps.MaxZoomService();
  map = new google.maps.Map(document.getElementById('map'), {
    center: {
      lat: -37.219331,
      lng: -43.777096
    },
    zoom: 10,
    mapTypeId: 'satellite',
  });

  map.addListener('center_changed', function() {
    maxZoomService.getMaxZoomAtLatLng(map.getCenter(), function(response) {
      if (response.status !== 'OK') {
        console.log('Error in MaxZoomService :(');
      } else {
        let currentZoom = map.getZoom();
        if (currentZoom > (response.zoom+1)) {
          console.log('Zoom out to get imagery: ' + currentZoom + ' -> ' + (response.zoom +1));
          map.setZoom(response.zoom + 1);
        }
        map.setOptions({
          maxZoom: response.zoom + 1
        });
      }
    });
  });
}