效果 官方示例 github地址
1. 安装leaflet.markercluster插件
npm install leaflet.markercluster -S
**
2. 在项目中引入leaflet.markercluster和样式文件
**
import 'leaflet.markercluster/dist/MarkerCluster.css'
import 'leaflet.markercluster/dist/MarkerCluster.Default.css'
import 'leaflet.markercluster'
3. 在data中注册图层组
export default {
name: 'Map',
data () {
return {
LayerMarkGroup: this.$L.markerClusterGroup({
// 当在最大缩放级别点击一个聚合点时,会将其蜘蛛化,以便看到包含的所有标记
spiderfyOnMaxZoom: true,
// 当鼠标经过聚合点时,显示包含的标记围成的范围
showCoverageOnHover: false,
// 点击一个聚合点时,快捷缩放到一个对应范围适合显示的zoom级别
// zoomToBoundsOnClick: false,
chunkedLoading: true,
// 一个聚合点的最大影响半径(px),默认为80
maxClusterRadius: 210,
// 平滑的拆分/合并聚合点的子项
animate: true,
// 定义一个函数去创建聚合点的图标
iconCreateFunction: (cluster) => {
let curMarkers = cluster.getAllChildMarkers();
let n = 0;
curMarkers.forEach((item, index) => {
n += 1;
});
let className = 'yccluster';
const img = require('@/assets/images/home/yc.png');
// 图标创建方式1
return L.divIcon({html: `<span>液厂</span><div style="background-color: rgba(141, 93, 203, 1); margin: 0; border-radius: 5px;"><span>${n}</span><div">`, className: className, iconSize: this.$L.point(70, 30)});
// 图标创建方式2
// return this.$L.icon({
// iconUrl: require('@/assets/images/home/gyyh.png'),
// iconSize: [25, 25],
// opacity: 1
// // iconAnchor: [4, 29],
// });
}
})
}
}
}
4. 图层组添加聚合点数据,挂载到地图上
data.forEach(item => {
this.LayerMarkGroup.addLayer(this.getMarker(item))
})
this.LayerMarkGroup.addTo(this.map)
getMarker() {
const marker = this.$L.marker(item.latlng, {
icon: this.$L.icon({
iconUrl: zoom < 9 ? iconImg : markerImg,
iconSize: [10, 10],
opacity: 1,
iconAnchor: [5, -5],
popupAnchor: [5, 0]
}),
item: item
})
marker.on('mouseover', () => {
// 鼠标移入事件
marker.bindPopup(`<div class="cd-span">${item.name}</div>
`, { className: 'mypopup' }).openPopup();
});
marker.on('mouseout', () => {
// 鼠标移出事件
marker.closePopup();
});
marker.on('click', () => {
// 点击事件
this.$router.push({ name: 'DownstreamDetail', params: {type: type, item: item} });
});
return marker;
}
5. 清空聚合点数据图层
this.LayerMarkGroup.clearLayers();