首页 > 解决方案 > 为了使用聚类,我是否需要向我的地图添加源?

问题描述

我想从 mapbox 向我的地图添加聚类,我按照他们的建议进行了入门操作:

https://www.mapbox.com/install/js/cdn-add/

现在我有了一张地图,我还添加了一些我自己的标记,这些标记是来自我的后端的用户,它们有纬度和经度。

所以我有一张地图和一些标记。

现在,我想添加聚类,在示例中:

https://docs.mapbox.com/mapbox-gl-js/example/cluster/

他们添加了一个来源:

map.addSource("earthquakes", {
})

我没有,目前我认为我什至不需要。因为我可以看到瓷砖和我的标记。

我想添加一个来源,但哪个来源?我不需要来源,我已经有了我需要的东西,瓷砖和标记......但是集群选项在地图上的 addSource 方法中。所以..我在这里迷路了。

这就是他们在示例中显示的内容,但正如我所说,我没有或不需要任何其他来源,因为我已经看到了瓷砖和我的标记,我只想进行聚类。

map.addSource("earthquakes", {
type: "geojson",
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)
});```

标签: javascriptmapbox

解决方案


我找到了解决方案,

我必须像这样从我的用户创建一个 geoJson 对象:

  const geoJsonMarkers = users.map( (place, i ) => {
    const [placeLng, placeLat] = place.location.coordinates;
    const position = { lat: placeLat, lng: placeLng };
    return {
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [position.lng, position.lat]
      },
      "properties": {
        "name": place.name
      }
    }
  })
  const usersArray = {
    "features": geoJsonMarkers
  }

然后将它传递给源的数据属性,如下所示:

  map.on('load', function() {
    // 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("users", {
    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: usersArray,
    cluster: true,
    clusterMaxZoom: 14, // Max zoom to cluster points on
    clusterRadius: 50 // Radius of each cluster when clustering points (defaults to 50)
    });
     ...

addSource 名称是任意的,在我的情况下可以是任何用户,所以我称之为用户。


推荐阅读