Leaflet.js setMaxBounds ignores southern bound

2019-07-04 01:38发布

问题:

Using Leaflet.js for an open-source map project, but I need to set specific bounds the user can't move beyond. The maxBounds property of the map object works as expected on the north, east and west directions- but it lets me scroll forever southward.

In the fiddle, the green background reveals where the bound should end, and I've added an on-click alert of the latitude for checking.

http://jsfiddle.net/7m7n7/

var map = L.map('map', {
maxZoom: 4,
minZoom: 1,
maxBounds: [
    //south west
    [-85.07815906717186, -179.97802734374997],
    //north east
    [-60.413852350464914, 39.8583984375]
]
}).setView([-72.5, -110], 1);

L.tileLayer(
    'http://{s}.tile.cloudmade.com/{API}/998/256/{z}/{x}/{y}.png', 
    { maxZoom: 18 }).addTo(map);

回答1:

When you use setBounds then leaflet called L.Map.panInsideBounds with your bounds, where are you trying get projection: viewSw = this.project(viewBounds.getSouthWest()), which use next code for default projection:

project: function (latlng) { // (LatLng) -> Point
    var d = L.LatLng.DEG_TO_RAD,
    max = this.MAX_LATITUDE,
    lat = Math.max(Math.min(max, latlng.lat), -max),
    x = latlng.lng * d,
    y = lat * d;

    y = Math.log(Math.tan((Math.PI / 4) + (y / 2)));

    return new L.Point(x, y);
}

So there are Math.max(Math.min(max, latlng.lat), -max) can't be more then max or min value and viewSw became equal to max value and real bounds not fixed.

This issue was fixed. You can use version from master or wait when next realise will be come.