javascript - 单张 OSM : Center mapview on polygon

标签 javascript html openstreetmap leaflet

我想生成一个包含 Leaflet 库的 html 文件,以显示带有多边形的 OpenStreetMap View 。 map 上的多边形应居中。为此,我遵循了 this讨论,但我仍然不清楚如何将任意多边形居中并自动缩放。自动缩放对我来说意味着多边形完全在可见 map 摘录中并填充它。

例如,这将是期望的结果:

enter image description here

到目前为止,这是我的代码:

    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

最佳答案

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

map.fitBounds(poly.getBounds());

(doc)。

关于javascript - 单张 OSM : Center mapview on polygon,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20948318/

相关文章:

javascript - 如何使用 Angular ui-select 过滤两个字段中的数据?

html - 浏览器调整大小时文本溢出

html - CSS:如何将按钮位置设置在html表格的右侧

postgresql - 使用 Nominatim db 连接任何 OSM 路由器/方向引擎

ruby-on-rails - ActiveResource 应忽略根 xml 元素

javascript - 即 8 : JS call to new Image() fails when the code is run in a popup window

javascript - 在 Redux Reducer 达到状态之前格式化日期

函数内部的Javascript调用函数

javascript - 无法将数据从 PHP 传递到 AJAX

leaflet - 在传单js的搜索框中选择地址后获取地址详细信息