Fit map to bounds exactly

社会主义新天地 提交于 2020-07-09 03:38:38

问题


Is there a way to fit the map exactly to bounds? (or as close a possible).

For example, in this jsfiddle, even without padding the map leaves a lot of padding above and below the points:

http://jsfiddle.net/BC7q4/444/

map.fitBounds(bounds);

$('#fit1').click(function(){ map.fitBounds(bounds); });
$('#fit2').click(function(){ map.fitBounds(bounds, {padding: [50, 50]}); });

I'm trying to fit a map as precisely as possible to a set of bounds that closely match the map shape without all the extra padding.

Setting a map's ne corner and sw corner would work as well, but I don't think that functionality exists.


回答1:


You are very probably looking for the map zoomSnap option:

Forces the map's zoom level to always be a multiple of this, particularly right after a fitBounds() or a pinch-zoom. By default, the zoom level snaps to the nearest integer; lower values (e.g. 0.5 or 0.1) allow for greater granularity. A value of 0 means the zoom level will not be snapped after fitBounds or a pinch-zoom.

Because its default value is 1, after your fitBounds the map will floor down the zoom value to the closest available integer value, hence possibly introducing more padding around your bounds.

By specifiying zoomSnap: 0, you ask the map not to snap the zoom value:

var map = L.map('map', {
  zoomSnap: 0 // http://leafletjs.com/reference.html#map-zoomsnap
}).setView([51.505, -0.09], 5);

// add an OpenStreetMap tile layer
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
  attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);

var southWest = new L.LatLng(40.712, -74.227),
  northEast = new L.LatLng(40.774, -74.125),
  bounds = new L.LatLngBounds(southWest, northEast);

L.marker([40.712, -74.227]).addTo(map);
L.marker([40.774, -74.125]).addTo(map);

map.fitBounds(bounds);

$('#fit1').click(function() {
  map.fitBounds(bounds);
});
$('#fit2').click(function() {
  map.fitBounds(bounds, {
    padding: [50, 50]
  });
});
body {
  padding: 0;
  margin: 0;
}

#map {
  height: 300px;
  margin-top: 10px;
}
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.2.0/dist/leaflet.css">
<script src="https://unpkg.com/leaflet@1.2.0/dist/leaflet-src.js"></script>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>

<button id="fit1">fit without bounds</button>
<button id="fit2">fit with bounds</button>
<div id="map"></div>


来源:https://stackoverflow.com/questions/46942988/fit-map-to-bounds-exactly

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