【问题标题】:Leaflet OSM: Center mapview on polygonLeaflet OSM:在多边形上居中地图视图
【发布时间】: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


    【解决方案1】:

    不完全居中,但如果您希望地图适合多边形:

    map.fitBounds(poly.getBounds());
    

    (doc).

    【讨论】:

    • 我会推荐包含一个maxZoom -> map.fitBounds(poly.getBounds(),{maxZoom:12}); fitBounds()map.setView(poly.getBounds().getCenter()) 好,但真的想放大:)
    【解决方案2】:

    要使多个多边形居中很高兴知道.fitBounds 也接受一个数组作为参数,因此您可以这样做:

    const poly = [polygonA,polygonB,polygonC]; 
    
    const bounds = poly.map(p=>p.getBounds());
    
    mymap.fitBounds(bounds);
    

    【讨论】:

      猜你喜欢
      • 2016-08-10
      • 1970-01-01
      • 2017-11-13
      • 2019-08-01
      • 1970-01-01
      • 2017-04-22
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多