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

Javascript map.fitBounds动态重新调整地图视图以在MapBox中显示可见的要素,javascript,mapbox,Javascript,Mapbox,我的地图包含多个要素,所有这些要素的ID都存储在一个数组中:featureID 我的应用程序包含一个按钮,用于切换某些功能的可见性 我正在开发一个JavaScript函数reCenter(),以遵循此切换。此功能根据现在可见的要素边界“缩小”并重新调整地图视图 function reCenter() { // new array for visible features var visibleFeatures = []; // retrieve the features which are

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

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

我正在开发一个JavaScript函数
reCenter()
,以遵循此切换。此功能根据现在可见的要素边界“缩小”并重新调整地图视图

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
    });
}
函数重新居中(){
//用于可见特征的新阵列
var visibleFeatures=[];
//检索可见的功能并将其放入新阵列中
对于(var i=0;i
尽管实施了上述规定并遵循了在中提供的指导。我收到以下错误:
TypeError:this.\u sw未定义


如何最好地动态检索可视特征的所有坐标并将其传递到
map.fitBounds()

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

它提供了一个方法bbox()

它需要一些功能集,并会自动为您计算bbox。并将最后一个bbox设置为fitbounds

前面有一个类似的问题:

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

它提供了一个方法bbox()

它需要一些功能集,并会自动为您计算bbox。并将最后一个bbox设置为fitbounds

前面有一个类似的问题:

获取所有功能并创建FeatureCollection,然后使用Turp.js中的bbox函数获取FeatureCollection的边界。我是这样做的: 注意:如果您的坐标不是wgs84,请使用toWgs84

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)));

获取您的所有功能并创建FeatureCollection,然后使用turp.js中的bbox函数获取FeatureCollection的边界。我是这样做的: 注意:如果您的坐标不是wgs84,请使用toWgs84

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)));