【问题标题】:map.fitBounds to dynamically refit map view to display visibile features in MapBoxmap.fitBounds 动态调整地图视图以在 MapBox 中显示可见功能
【发布时间】:2020-08-08 00:25:04
【问题描述】:

我的地图包含多个特征,所有这些特征的 id 都存储在一个数组中:featureIds

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

我正在开发一个 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
    });
}

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

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

【问题讨论】:

    标签: javascript mapbox


    【解决方案1】:

    获取所有功能并创建 FeatureCollection,并使用 Turf.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)));
    

    【讨论】:

      【解决方案2】:

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

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

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

      之前有人问过类似的问题: Mapbox GL JS getBounds()/fitBounds()

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-07-08
        • 1970-01-01
        • 1970-01-01
        • 2016-06-09
        • 1970-01-01
        • 2014-10-29
        • 1970-01-01
        相关资源
        最近更新 更多