Search code examples
google-mapsgoogle-maps-api-3fitbounds

How to fitBounds groundOverlay google maps api more closely


I created a groundOverlay that uses the Google Maps API. I'd like to make the ground fit much as possible. I also tried to use padding option or zoom++ but it not work as I expected.

Current:

enter image description here

Expected:

enter image description here

Re-production: https://jsfiddle.net/abinhho/5kvtfpeo/10/


Solution

  • The problem is quite easy to understand. fitBounds() will fit the map to the given bounds and make sure the entire bounds are visible within the map viewport. So it will choose the best zoom level (and center point) to achieve that.

    It might display with a good margin around, but would not fit anymore if you zoom in one more level. Try it with the below example.

    var historicalOverlay;
    
    function initMap() {
      var map = new google.maps.Map(document.getElementById('map'), {
        center: {lat: 40.740, lng: -74.18},
        zoomControl: true
      });
    
      var imageBounds = {
        north: 40.773941,
        south: 40.712216,
        east: -74.12544,
        west: -74.22655
      };
      
      historicalOverlay = new google.maps.GroundOverlay(
          'https://www.lib.utexas.edu/maps/historical/newark_nj_1922.jpg',
          imageBounds);
          
      historicalOverlay.setMap(map);
      
      map.fitBounds(historicalOverlay.getBounds());
    }
    #map {
      height: 220px;
    }
    <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=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap" async defer></script>

    The only thing you could do about that, is to use the padding interface, maybe with a negative value. But then you might have the opposite result; the image might not be shown entirely.

    var historicalOverlay;
    
    function initMap() {
      var map = new google.maps.Map(document.getElementById('map'), {
        center: {lat: 40.740, lng: -74.18},
        zoomControl: true
      });
    
      var imageBounds = {
        north: 40.773941,
        south: 40.712216,
        east: -74.12544,
        west: -74.22655
      };
      
      historicalOverlay = new google.maps.GroundOverlay(
          'https://www.lib.utexas.edu/maps/historical/newark_nj_1922.jpg',
          imageBounds);
          
      historicalOverlay.setMap(map);
      
      map.fitBounds(historicalOverlay.getBounds(), {'bottom': -50, 'left': -50, 'top': -50, 'right': -50});
    }
    #map {
      height: 180px;
    }
    <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=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap" async defer></script>