【发布时间】:2014-01-23 18:13:50
【问题描述】:
我想生成一个包含Leaflet 库的html 文件,以显示带有多边形的OpenStreetMap 视图。地图上的多边形应该居中。为此,我关注了this 的讨论,但我仍然不清楚如何将任意多边形居中并自动缩放。自动缩放对我来说意味着多边形完全在可见地图摘录中并填充它。
例如,这将是期望的结果:
这是我目前的代码:
var map;
var ajaxRequest;
var plotlist;
var plotlayers=[];
function initmap() {
// set up the map
map = new L.Map('map');
/* --- Replace for different URL for OSM tiles */
var url_base ='URL_TO_MY_OPENSTREETMAPS_SERVER';
var latitude = 50.2222;
var longtitude = 3.322343;
var poly = L.polygon([
[50.2222, 3.322343],
[50.2322, 3.323353],
[...]
]);
// create the tile layer with correct attribution
var osmUrl=url_base+'{z}/{x}/{y}.png';
var osmAttrib='Map data ɠOpenStreetMap contributors';
var osm = new L.TileLayer(osmUrl, {minZoom: 4, maxZoom: 20, attribution: osmAttrib});
// start the map at specific point
map.setView(new L.LatLng(latitude, longtitude),15);
map.addLayer(osm);
poly.addTo(map);
}
如果有我可以使用的Leaflet 的“板载”方法,那就太好了。如何计算多边形的中心很清楚(例如here),但也许已经有我可以使用的方法。
解决方案:
// start the map at specific point
// map.setView(new L.LatLng(latitude, longtitude),15); <- Remove this line
map.addLayer(osm);
poly.addTo(map);
map.fitBounds(poly.getBounds()); // <- Add this line
【问题讨论】:
标签: javascript html openstreetmap leaflet