首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >用于在MapBox中动态重新调整地图视图以显示可见要素的map.fitBounds

用于在MapBox中动态重新调整地图视图以显示可见要素的map.fitBounds
EN

Stack Overflow用户
提问于 2020-04-24 20:19:07
回答 2查看 162关注 0票数 0

我的地图包含多个要素,所有这些要素的in都存储在一个数组中:featureIds

我的应用程序包含一个按钮,用于切换某些功能的可见性。

我正在编写一个JavaScript函数reCenter()来遵循这个切换。此函数可根据现在可见的要素的边界来缩小和重新调整地图视图。

代码语言:javascript
运行
复制
function reCenter() {

// new array for visible features 
var visibleFeatures = [];

// retrieve the features which are visible and put them into the new array
    for (var i = 0; i < featureIds.length; i++) {

        if (map.getLayoutProperty(featureIds[i], "visibility") == "visible") {

            visibleFeatures.push(map.queryRenderedFeatures(featureIds[i]));
        }

    }

    // new array to store coordinates
    coordinates = [];


    // push coordinates for each visible feature to coordinates array    
    for (var j = 0; j < visibleFeatures.length; j++) {

        coordinates.push(coord.geometry.coordinates);

    }

    // do fit as shown here : https://docs.mapbox.com/mapbox-gl-js/example/zoomto-linestring/
    var bounds = coordinates.reduce(function (bounds, coord) {
        return bounds.extend(coord);
    }, new mapboxgl.LngLatBounds(coordinates[0], coordinates[0]));

    map.fitBounds(bounds, {
        padding: 20
    });
}

尽管实施了上述内容并遵循了https://docs.mapbox.com/mapbox-gl-js/example/zoomto-linestring/提供的指导。我收到以下错误:TypeError: this._sw is undefined

如何动态地检索可见特征的所有坐标并将它们传递到map.fitBounds()

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-02-12 21:55:54

获取所有特性并创建一个FeatureCollection,然后使用Turf.js中的bbox函数获取FeatureCollection的界限。我是这样做的:注意:如果坐标不是wgs84,请使用toWgs84。

代码语言:javascript
运行
复制
const features = [
    {
         type: 'Feature',
         geometry: {
             type: 'Polygon',
             coordinates: [
                 [your_feature_s_coordinates],
                 [...],
             ]
         }
     },
     {another feature}
 ]

 const FeatureCollection = {
     type: "FeatureCollection",
     features: features
 };

 map.fitBounds(bbox(toWgs84(FeatureCollection)));
票数 1
EN

Stack Overflow用户

发布于 2020-09-05 19:32:51

试试Turf.js: js是一个用于空间分析的开源JavaScript库。

它提供了一种方法bbox (http://turfjs.org/docs/#bbox)

它采用了一些特性集,并将自动为您计算bbox。并将最终的bbox设置为fitbounds。

前面还有一个类似的问题:Mapbox GL JS getBounds()/fitBounds()

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61408215

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档