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

吃可爱长大的小学妹 提交于 2019-11-27 12:23:06

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);

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

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> });

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);
        }
    }

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)

I will provide a more generic solution for this issue. If we have a position e.g. marker.getPosition(), we can find a another position (x, y) pixel away from it using this function.

function extendedLocation(position, x, y) {
    var projection = map.getProjection();
    var newMarkerX = projection.fromLatLngToPoint(position).x + x/(Math.pow(2, map.getZoom()))
    var newMarkerY = projection.fromLatLngToPoint(position).y + y/(Math.pow(2, map.getZoom()))
    var newMarkerPoint = new google.maps.Point(newMarkerX, newMarkerY);
    return projection.fromPointToLatLng(newMarkerPoint)
}

Note: positive x is in right direction and positive y is in down direction. So, in general case, to bring marker in view, we need to pass negative value of y e.g. extendedLocation(marker.getPosition(), 4, -18)

If you have a persistent slider or any such element at the top of suppose 30 px height, just use y parameter in the function as -30.

A more generalised function can be created which return array of 4 points, each (x, y) pixels away from the given pointing up, down, right and left direction.

function getAllExtendedPosition(position, x, y){
   var positionArray = [];
   postitionArray.push(extendedLocation(position, x, y);
   postitionArray.push(extendedLocation(position, -x, -y);
   postitionArray.push(extendedLocation(position, -x, y);
   postitionArray.push(extendedLocation(position, x, -y);
   return positionArray
}

Another way to do this would be to extend your boundaries with an additional LatLong point a calculated distance away. The google.maps.LatLngBounds() object has functions to get the SouthWest and NorthEast points of the bounding box, and that can be used to calculate a distance X miles North, South, East or West.

For example, if you were trying to push your markers to the right to account for overlay elements on the left side of the map, you might try the following:

// create your LatLngBounds object, like you're already probably doing
var bounds = new google.maps.LatLngBounds();

// for each marker call bounds.extend(pos) to extend the base boundaries

// once your loop is complete
// *** add a calculated LatLng point to the west of your boundary ***
bounds.extend(new google.maps.LatLng(bounds.getSouthWest().lat(), bounds.getSouthWest().lng() - .9));

// finally, center your map on the modified boundaries
map.fitBounds(bounds);

In the example above, adding a LatLong point to the bounds by subtracting .9 from the longitude of the western-most point moves the boundary about 52 miles further to the west.

A whole point (pos.lng() - 1.0) is about 58 miles, so you can either guess a good distance or use some other method to calculate that longitudinal offset when figuring out what kind of padding you need.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!