Mapbox 适合带有簇的标记

问题描述 投票:0回答:1

我正在尝试弄清楚如何自动缩放/飞到通过 geojson 文件加载的地图上的一组标记,但具有聚类功能。

我的地图、标记和聚类与来自 Mapbox 的 示例代码一起使用。

但是我无法弄清楚如何从 geojson 源创建坐标数组,以便我可以运行 fitBounds

const map = new mapboxgl.Map({
container: 'map',
// Choose from Mapbox's core styles, or make your own style with Mapbox Studio
style: 'mapbox://styles/mapbox/dark-v11',
center: [-103.5917, 40.6699],
zoom: 3
});
 
map.on('load', () => {
// Add a new source from our GeoJSON data and
// set the 'cluster' option to true. GL-JS will
// add the point_count property to your source data.
map.addSource('earthquakes', {
type: 'geojson',
// Point to GeoJSON data. This example visualizes all M1.0+ earthquakes
// from 12/22/15 to 1/21/16 as logged by USGS' Earthquake hazards program.
data: 'https://docs.mapbox.com/mapbox-gl-js/assets/earthquakes.geojson',
cluster: true,
clusterMaxZoom: 14, // Max zoom to cluster points on
clusterRadius: 50 // Radius of each cluster when clustering points (defaults to 50)
});
 
map.addLayer({
id: 'clusters',
type: 'circle',
source: 'earthquakes',
filter: ['has', 'point_count'],
paint: {
// Use step expressions (https://docs.mapbox.com/style-spec/reference/expressions/#step)
// with three steps to implement three types of circles:
//   * Blue, 20px circles when point count is less than 100
//   * Yellow, 30px circles when point count is between 100 and 750
//   * Pink, 40px circles when point count is greater than or equal to 750
'circle-color': [
'step',
['get', 'point_count'],
'#51bbd6',
100,
'#f1f075',
750,
'#f28cb1'
],
'circle-radius': [
'step',
['get', 'point_count'],
20,
100,
30,
750,
40
]
}
});
 
map.addLayer({
id: 'cluster-count',
type: 'symbol',
source: 'earthquakes',
filter: ['has', 'point_count'],
layout: {
'text-field': ['get', 'point_count_abbreviated'],
'text-font': ['DIN Offc Pro Medium', 'Arial Unicode MS Bold'],
'text-size': 12
}
});
 
map.addLayer({
id: 'unclustered-point',
type: 'circle',
source: 'earthquakes',
filter: ['!', ['has', 'point_count']],
paint: {
'circle-color': '#11b4da',
'circle-radius': 4,
'circle-stroke-width': 1,
'circle-stroke-color': '#fff'
}
});

我认为这是一个相当常见的要求,并且确实应该有一个自己的例子。

javascript geojson mapbox-gl-js
1个回答
0
投票

您可以通过

'data'
事件访问集群加载的数据。
正如Docs中所指定的,只要有数据加载或更改,它就会触发。

map.on('data', 'clusters', (e) => {
  // e.features = geojson features with type, properties, and geometry, 
  //              in this case each feature is a cluster.

  // Calculate the bounding box for the cluster 
  const bounds = new 
  mapboxgl.LngLatBounds(e.features[0].geometry.coordinates, 
  e.features[0].geometry.coordinates);

  // Fit the map to the calculated bounds
  map.fitBounds(bounds, { padding: 20 });
  map.setZoom(7);
})
© www.soinside.com 2019 - 2024. All rights reserved.