Google Maps API 3 fitBounds padding - ensure markers are not obscured by overlaid controls

26,163

Solution 1

This is some kind of a hack-ish solution, but after the fitBounds, you could zoom one level out, so you get enough padding for your markers.

Assume map variable is your reference to the map object;

map.setZoom(map.getZoom() - 1);

Solution 2

As of June 2017 the Maps JavaScript API is supporting the padding parameter in the fitBounds() method.

fitBounds(bounds:LatLngBounds|LatLngBoundsLiteral, padding?:number)

Please refer to the documentation for further details

https://developers.google.com/maps/documentation/javascript/reference#Map

Solution 3

I solved this problem by extended the map bounds to include a latlng that sufficiently pushed the markers into view.

Firstly you need to create an overlay view

var overlayHelper = new google.maps.OverlayView();
overlayHelper.onAdd = function() {};
overlayHelper.onRemove = function() {};
overlayHelper.draw = function() {};
overlayHelper.setMap(map);

Once you have an overlay helper you need to get the map projection and perform calcs based on that.

Note that the control that I have on my map is a 420 pixel wide, 100% height div on the far right of the map. You will obviously need to change the code to accomodate your controls.

var mapCanvas = $("#map_canvas"),
    controlLeft = mapCanvas.width() - 420, // canvas width minus width of the overlayed control
    projection = overlayHelper.getProjection(),
    widestPoint = 0, 
    latlng, 
    point;

// the markers were created elsewhere and already extended the bounds on creation
map.fitBounds(mapBounds);

// check if any markers are hidden behind the overlayed control
for (var m in markers) {
    point = projection.fromLatLngToContainerPixel(markers[m].getPosition());
    if (point.x > controlLeft && point.x > widestPoint) {
        widestPoint = point.x;
    }
}

if (widestPoint > 0) {
    point = new google.maps.Point(
                mapCanvas.width() + (widestPoint - controlLeft), 
                mapCanvas.height() / 2); // middle of map height, since we only want to reposition bounds to the left and not up and down

    latlng = projection.fromContainerPixelToLatLng(point);
    mapBounds.extend(latlng);
    map.fitBounds(mapBounds);
}

If you're doing this when the map loads for the first time, then you will need to wrap this in a map event to wait for idle. This allows the overlay view to initialize. Don't include the overlay helper creation within the event callback.

google.maps.event.addListenerOnce(map, 'idle', function() { <above code> });

Solution 4

Updated

Google Maps API now supports a native "padding" param in the fitBounds method (from version 3.32, correct me if earlier).

I had no chance yet to test it, but if you're able to upgrade - I would recommend to use a native way. If you're using version < 3.32 and can't upgrade - my solution is for you.


I took working solution by erzzo and improved it a little bit.
Example

fitBoundsWithPadding(googleMapInstance, PolygonLatLngBounds, {left:250, bottom:10});

Arguments description:

  1. gMap - google map instance
  2. bounds - google maps LatLngBounds object to fit
  3. paddingXY - Object Literal: 2 possible formats:
    • {x, y} - for horizontal and vertical paddings (x=left=right, y=top=bottom)
    • {left, right, top, bottom}

function listing to copy

function fitBoundsWithPadding(gMap, bounds, paddingXY) {
        var projection = gMap.getProjection();
        if (projection) {
            if (!$.isPlainObject(paddingXY))
                paddingXY = {x: 0, y: 0};

            var paddings = {
                top: 0,
                right: 0,
                bottom: 0,
                left: 0
            };

            if (paddingXY.left){
                paddings.left = paddingXY.left;
            } else if (paddingXY.x) {
                paddings.left = paddingXY.x;
                paddings.right = paddingXY.x;
            }

            if (paddingXY.right){
                paddings.right = paddingXY.right;
            }

            if (paddingXY.top){
                paddings.top = paddingXY.top;
            } else if (paddingXY.y) {
                paddings.top = paddingXY.y;
                paddings.bottom = paddingXY.y;
            }

            if (paddingXY.bottom){
                paddings.bottom = paddingXY.bottom;
            }

            // copying the bounds object, since we will extend it
            bounds = new google.maps.LatLngBounds(bounds.getSouthWest(), bounds.getNorthEast());

            // SW
            var point1 = projection.fromLatLngToPoint(bounds.getSouthWest());


            // we must call fitBounds 2 times - first is necessary to set up a projection with initial (actual) bounds
            // and then calculate new bounds by adding our pixel-sized paddings to the resulting viewport
            gMap.fitBounds(bounds);

            var point2 = new google.maps.Point(
                ( (typeof(paddings.left) == 'number' ? paddings.left : 0) / Math.pow(2, gMap.getZoom()) ) || 0,
                ( (typeof(paddings.bottom) == 'number' ? paddings.bottom : 0) / Math.pow(2, gMap.getZoom()) ) || 0
            );

            var newPoint = projection.fromPointToLatLng(new google.maps.Point(
                point1.x - point2.x,
                point1.y + point2.y
            ));

            bounds.extend(newPoint);

            // NE
            point1 = projection.fromLatLngToPoint(bounds.getNorthEast());
            point2 = new google.maps.Point(
                ( (typeof(paddings.right) == 'number' ? paddings.right : 0) / Math.pow(2, gMap.getZoom()) ) || 0,
                ( (typeof(paddings.top) == 'number' ? paddings.top : 0) / Math.pow(2, gMap.getZoom()) ) || 0
            );
            newPoint = projection.fromPointToLatLng(new google.maps.Point(
                point1.x + point2.x,
                point1.y - point2.y
            ));

            bounds.extend(newPoint);

            gMap.fitBounds(bounds);
        }
    }

Solution 5

You can use map.fitBounds() with API V3 with the same padding syntax as you mentioned with map.showBounds().

Simply using map.fitBounds(bounds, {top:30,right:10,left:50}); worked for me.

(this could be comment to xomena's or Roman86' post, I don't have enough reputation to comment)

Share:
26,163
jsurf
Author by

jsurf

Updated on February 26, 2021

Comments

  • jsurf
    jsurf about 3 years

    I'd like to be able add padding to a map view after calling a map.fitBounds(), so all markers can be visible regardless of map controls or things like sliding panels that would cover markers when opened. Leaftlet has an option to add padding to fitBounds, but Google Maps does not.

    Sometimes the northmost markers partially hide above the viewport. The westmost markers also often lay under the zoom slider. With API 2 it was possible to form a virtual viewport by reducing given paddings from the map viewport and then call the method showBounds() to calculate and perform zooming and centering based on that virtual viewport:

    map.showBounds(bounds, {top:30,right:10,left:50});
    

    A working example of this for API 2 can be found here under the showBounds() example link.

    I cannot find similar functionality in API V3, but hopefully there is another way this can be accomplished. Maybe I could grab the northeast and southwest points, then add fake coordinates to extend the bounds further after including them?

    UPDATE

    (Codepen in case the code below doesn't work)

    function initMap() {
      var map = new google.maps.Map(document.getElementById('map'), {
        draggable: true,
        streetViewControl: false,
        zoomControl: false
      });
    
      var marker1 = new google.maps.Marker({
        position: {lat: 37, lng: -121},
        map: map,
      });
    
      var marker2 = new google.maps.Marker({
        position: {lat: 39.3, lng: -122},
        map: map,
      });
     
      var bounds = new google.maps.LatLngBounds();
      bounds.extend(marker1.position);
      bounds.extend(marker2.position);
      map.fitBounds(bounds);
    }
    #map {
      height: 640px;
      width: 360px;
    }
    #overlays {
      position: absolute;
      height: 50px;
      width: 340px;
      background: white;
      margin: -80px 10px;
      text-align: center;
      line-height: 50px;
    }
    /* Optional: Makes the sample page fill the window. */
    html, body {
      height: 100%;
      margin: 0;
      padding: 0;
    }
    <html>
      <head>
        <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
        <meta charset="utf-8">
        <title>Simple markers</title>
    
      </head>
      <body>
        <div id="map"></div>
        <div id="overlays">Controls / Order pizza / ETA / etc.</div>
      
        <script async defer
        src="https://maps.googleapis.com/maps/api/js?&callback=initMap">
        </script>
      </body>
    </html>

    The problem is this:

    enter image description here

    I've tried adding a control as documented at Custom controls, but the map isn't exactly aware of it - see this fiddle forked from the Maps custom control example. One of the markers is still obscured by the control.