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

问题描述 投票:6回答:2

我正在使用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);
            }
        );

这很有效。但是,我现在想要对这些标记进行聚类,产生与使用图层找到的功能相同的效果,即

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

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

mapbox mapbox-gl mapbox-gl-js
2个回答
2
投票

回答自己的问题:

目前似乎根据mapbox的github:enter image description here这是不可能的

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


2
投票

此功能现在在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,
        });

这将推动mapbox对您的图标进行聚类,但是您需要告诉mapbox在对这些图标进行聚类时该做什么:

map.on( 'moveend', updateMarkers ); // moveend also considers zoomend

业务(因相关性而减少):

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 );
    }

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

© www.soinside.com 2019 - 2024. All rights reserved.