我之前遇到了同样的问题,我使用以下方法修复它:
-
拟合边界因为它将填充量(以像素为单位)添加到给定的边界。
-
请求动画帧:在其回调中,我收到了 getBounds 并将其设置为最大边界(技巧)
更新的代码片段:
<script>
mapboxgl.accessToken = 'pk.eyJ1IjoiYnBhY2h1Y2EiLCJhIjoiY2lxbGNwaXdmMDAweGZxbmg5OGx2YWo5aSJ9.zda7KLJF3TH84UU6OhW16w';
const map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v9',
center: [-73.9774108244587, 40.820698485268366],
zoom: 11.6
});
map.on('load', function () {
const padding = { left: 300, right: 100, top: 100, bottom: 30 }; //<--- padding
const bounds = {
"n": 40.896790957065434,
"s": 40.76021859203365,
"e": -73.85756962495667,
"w": -74.09102645202957
}
const maxBounds = [[bounds.w, bounds.s], [bounds.e, bounds.n]];
//<---- notice here--->
map.fitBounds(maxBounds, {
padding, //<--- used here
linear: true,
duration: 0
});
map.showPadding = true
//<---- notice here--->
requestAnimationFrame(() => {
const getBoundsFromViewport = map.getBounds();
map.setMaxBounds(getBoundsFromViewport);
});
const boundsRect = [
[bounds.e, bounds.n],
[bounds.w, bounds.n],
[bounds.w, bounds.s],
[bounds.e, bounds.s],
[bounds.e, bounds.n]
]
map.on('click', (e) => console.log('##', e.lngLat.toArray()))
map.addLayer({
'id': 'bounds',
'type': 'line',
'source': {
'type': 'geojson',
'data': {
'type': 'Feature',
'geometry': {
'type': 'LineString',
'coordinates': boundsRect
}
}
},
'paint': {
'line-color': '#000000',
'line-width': 10
},
'layout': {}
});
});
</script>
And it will like charm in your case too. Attaching screenshot:
试一试!