Javascript 传单OSM:多边形上的中心地图视图
我想生成一个html文件,包括Javascript 传单OSM:多边形上的中心地图视图,javascript,html,openstreetmap,leaflet,Javascript,Html,Openstreetmap,Leaflet,我想生成一个html文件,包括传单库,以显示带有多边形的OpenStreetMap视图。地图上的多边形应该居中。为此,我进行了讨论,但我仍然不清楚如何使任意多边形居中并自动缩放它。“自动缩放”对我来说意味着多边形完全位于可见地图摘录中并填充它 例如,这将是期望的结果: 这是我目前的代码: var map; var ajaxRequest; var plotlist; var plotlayers=[]; function initmap() {
传单
库,以显示带有多边形的OpenStreetMap
视图。地图上的多边形应该居中。为此,我进行了讨论,但我仍然不清楚如何使任意多边形居中并自动缩放它。“自动缩放”对我来说意味着多边形完全位于可见地图摘录中并填充它
例如,这将是期望的结果:
这是我目前的代码:
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);
}
特别是如果有我可以使用的传单
的“车载”方法,那就太好了。如何计算多边形的中心对于(例如)来说是很清楚的,但是可能已经有一些我可以使用的方法了
解决方案:
// 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
//在特定点启动映射
//地图设置视图(新L.LatLng(纬度,经度),15) 不完全居中,但如果希望将贴图拟合到多边形:
map.fitBounds(poly.getBounds());
()。要使多个多边形居中,最好知道。fitBounds
也接受数组作为参数,因此可以执行以下操作:
const poly = [polygonA,polygonB,polygonC];
const bounds = poly.map(p=>p.getBounds());
mymap.fitBounds(bounds);
我建议包含一个maxZoom
->map.fitBounds(poly.getBounds(),{maxZoom:12})
fitBounds()
优于map.setView(poly.getBounds().getCenter())
但确实想缩放:)