使用mapbox-gl-js聚类自定义html标记

Huw*_*ies 6 mapbox mapbox-gl mapbox-gl-js

我正在使用mapbox-gl-js API,我正在使用它来反应创建一些自定义标记,如下所示:

        let div = document.createElement('div');
        let marker = new mapboxgl.Marker(div, {
            offset: [ -20, 80 ]
        });

        marker.setLngLat(person.geometry.coordinates);

        render(
            <MapPersonIcon />,
            div,
            () => {
                marker.addTo(map);
            }
        );
Run Code Online (Sandbox Code Playgroud)

结果

这很有效.但是,我现在想要聚集这些标记,产生与图层中发现的功能相同的影响,即

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

集群

有谁知道这是否可行(希望也有自定义集群)或是否可以在即将发布的版本中使用?

Abr*_*kes 5

此功能现在在 Mapbox GL js 中 - https://docs.mapbox.com/mapbox-gl-js/example/cluster-html/

关键要点:

使用 设置数据源时map.addSource,请确保定义cluster: trueclusterRadius: int,如下所示:

        map.addSource( 'sourceName', {
            type: "geojson",
            data: {
                type: 'FeatureCollection',
                features: [JSON]
            },
            cluster: true,
            clusterRadius: 80,
        });
Run Code Online (Sandbox Code Playgroud)

这将推动 mapbox 对您的图标进行聚类,但是您需要告诉 mapbox 在对这些图标进行聚类时要执行的操作:

map.on( 'moveend', updateMarkers ); // moveend also considers zoomend
Run Code Online (Sandbox Code Playgroud)

业务(根据相关性进行了缩减):

function updateMarkers(){
    var features = map.querySourceFeatures( 'sourceName' );

    for ( var i = 0; i < features.length; i++ ) {
        var coords = features[ i ].geometry.coordinates;
        var props = features[ i ].properties;

        if ( props.cluster ){ // this property is only present when the feature is clustered
            // generate your clustered icon using props.point_count
            var el = document.createElement( 'div' );
            el.classList.add( 'mapCluster' );
            el.innerText = props.point_count;
            marker = new mapboxgl.Marker( { element: el } ).setLngLat( coords );

        } else { // feature is not clustered, create an icon for it
            var el = new Image();
            el.src = 'icon.png';
            el.classList.add( 'mapMarker' );
            el.dataset.type = props.type; // you can use custom data if you have assigned it in the GeoJSON data
            marker = new mapboxgl.Marker( { element: el } ).setLngLat( coords );
        }

        marker.addTo( map );
    }
Run Code Online (Sandbox Code Playgroud)

注意:不要复制粘贴此代码,而是将其与https://docs.mapbox.com/mapbox-gl-js/example/cluster-html/结合使用以获取全貌。希望这可以帮助!


Huw*_*ies 2

回答自己的问题:

目前,根据mapbox的github,这似乎是不可能的:在此输入图像描述

如果您想对标记进行聚类,则需要使用 Mapbox 的本机 Maki 图标(请参阅上面的示例图片和 URL),直到有可用于您的自定义 HTML 标记的插件为止。

  • 当我使用Leaflet时,我能够使用css来解决这个问题;我会覆盖默认的标记 CSS 并使用我自己的“背景图像”和样式来添加标记,效果非常好。有点令人沮丧的是,我无法像 GL 那样使用画布,并通过 Geojson/Javascript 将“本机”对象添加到地图中,但遗憾的是拒绝添加非本机元素。我将查看他们的源代码,看看他们如何添加标记,以及是否有明显的问题突出,并尝试实施解决方法。感谢您的调查。 (3认同)
  • @jberculo 我没有也不能。实施的时间成本在我的工作范围内不可用。我能想到的最好的方法是多层 - 基本上当一层位于另一层之上时创建边框外观 (3认同)