缩放 MapBox GL 地图以适合标记集

2024-05-07

假设我有以下 Mapbox 地图代码:

mapboxgl.accessToken = '<token>';
var map = new mapboxgl.Map({
    container: 'map',
    style: 'mapbox://styles/mapbox/satellite-v9',
    center: [-96, 37.8],
    zoom: 2,
    interactive: true
});

var geojson = {
    "type": "FeatureCollection",
    "features": [
        {
            "type": "Feature",
            "geometry": {
                "type": "Point",
                "coordinates": [-77.03238901390978, 38.913188059745586]
            },
            "properties": {
                "id": 1,
                "color": "#007cbf",
                "text": "1"
            }
        }, 
        {
            "type": "Feature",
            "geometry": {
                "type": "Point",
                "coordinates": [-78.03238901390978, 39.913188059745586]
            },
            "properties": {
                "id": 2,
                "color": "red",
                "text": "2"
            }
        }
    ]
}

map.on('style.load', function (e) {
    map.addSource('markers', {
        "type": "geojson",
        "data": geojson
    });
    geojson.features.forEach(function(marker){
        map.addLayer({
            "id": String(marker.properties.id)+'-circle',
            "source": "markers",
            "type": "circle",
            "paint": {
                "circle-radius": 20,
                "circle-color": marker.properties.color,
                "circle-opacity": 0.8,
                "circle-stroke-width": 0,
            },
            "filter": ["==", "id", marker.properties.id],
        });
        map.addLayer({
            "id": String(marker.properties.id)+'-text',
            "source": "markers",
            "type": "symbol",
            "layout": {
                'text-field': marker.properties.text,
                'text-size': 20
            },
            "filter": ["==", "id", marker.properties.id]
        })
    });
});

如何缩放地图以适应地图上的一组点?我找不到 mapboxgl 的任何解决方案。另外,我不能 100% 确定我应该为每个标记创建一个单独的图层,但我找不到一种方法将所有标记放入一个图层中。提前致谢。


我想你正在寻找的是map.fitBounds这将创建一个边界框以使地图视图适应坐标列表。

map.fitBounds([
  [-77.03238901390978, 38.913188059745586],
  [-78.03238901390978, 39.913188059745586]
]);

但是,如果源中可能有一堆点,因为它看起来基于您的代码,那么您需要首先将每个标记的所有坐标推送到数组中,然后使用coordinates.reduce

var coordinates = coords;

var bounds = coordinates.reduce(function(bounds, coord) {
  return bounds.extend(coord);
}, new mapboxgl.LngLatBounds(coordinates[0], coordinates[0]));

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

I have created a fiddle for you with this solution, how to fit mapbox bounds to a list of coords https://jsfiddle.net/jscastro76/vjkt7wyx/26/, it works your using your own code and coords. enter image description here enter image description here

关于为每个标记创建一个图层,您绝对应该尝试避免这种做法,并仅创建一个图层来托管所有标记。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

缩放 MapBox GL 地图以适合标记集 的相关文章

随机推荐