使用markerClusterGroup实现点聚合

336 阅读1分钟

效果: image.png

开发要求

点图层由geojson组成。由于点有多种类别每种类别都对应一个geojson,当用户选择一类点就将在图层上添加一个geojson图层。

书写原因

开始是添加n个geojosn图层,然后把这些图层添加到markerClusterGroup聚合图层。 随后发现当动态的增加或删除时,发现有些点不能聚合成功。 研究发现一个聚合图层对应一个geojson图层,多个geojson图层并不生效。

解决办法

新建geojosn图层,通过addData方法添加数据

代码展示

    let layer = null
    //遍历整合geojosn,整合成一个geojson图层
    for (let index = 0; index < geojsons.length; index++) {
        const geojson = geojsons[index];
        if(!geojson.iconUrl){
            geojson.iconUrl = "none:images/map/location.png"
        }
        //设置marker 一类点对应一类marker
        let marker = function (feature, latlng) {
            let code = feature.properties.redtypecode
            let iconUrl = _.filter(geojsons,(item) => {
                let arr = item.iconUrl.split(':')
                if(code === arr[0]){
                    return item.iconUrl
                } else {
                    return 'none:images/map/location.png'
                }
            })
            iconUrl = iconUrl[0].iconUrl.split(':')[1]
            let baseballIcon = L.icon({
                // iconUrl: iconUrl,
                iconUrl:'images/map/location.png',
                shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/images/marker-shadow.png',      
                iconSize: [25, 41],
                iconAnchor: [12, 41],
                popupAnchor: [1, -34],
                shadowSize: [41, 41]
            });
            return L.marker(latlng, {
                icon: baseballIcon,
                riseOnHover:true
            });
        }
        //建立geojosn图层
        //判断是否有layer,没有新建,有就往里面添加
        if(!layer){
            layer = L.geoJSON(geojson.data, {
                //循环设置图标样式
                pointToLayer: marker,
                onEachFeature: clickPoint
            })
        } else {
            layer.addData(geojson.data)
        }
        
    }
    // layer.addTo(map)
    return layer
  
}

//定义聚合图
 let heatMarkerLayer = L.markerClusterGroup({
    maxClusterRadius: 110, //A cluster will cover at most this many pixels from its center
    singleMarkerMode: false //true:单个marker显示聚合数字1,false:显示单个marker  
});
//添加图层
heatMarkerLayer.addLayer(layer);
this.map.addLayer(heatMarkerLayer);

使用:blog.csdn.net/duonibaby/a…