说明:
高德地图点聚合官方功能不能满足业务需求,此例子在完全自定义点聚合基础上增加悬浮与选中效果。预览图:
在线预览:
代码:
代码没有添加注释,只是自己的方式实现,如有疏漏,请多指正。
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
<title>高德完全自定义点聚合,可配置悬浮效果、选中效果</title>
<link rel="stylesheet" href="https://a.amap.com/jsapi_demos/static/demo-center/css/demo-center.css" />
<style>
html,
body,
#mapView {
height: 100%;
width: 100%;
}
.container {
width: 40px;
height: 40px;
background-color: blue;
border-radius: 50%;
color: #fff;
text-align: center;
line-height: 40px;
cursor: pointer;
transition: all 0.5s;
}
.container:hover {
background-color: green;
}
.selected {
background-color: orange;
}
</style>
</head>
<body>
<div id="mapView"></div>
<script type="text/javascript"
src="https://webapi.amap.com/maps?v=1.4.15&key=您申请的key值&plugin=AMap.MarkerClusterer"></script>
<script type="text/javascript">
const markers = [
{ lng: 121.478223, lat: 31.233467 },
{ lng: 121.478223, lat: 31.233467 },
{ lng: 121.478223, lat: 31.233467 },
{ lng: 121.468181, lat: 31.231853 },
{ lng: 121.468181, lat: 31.231853 },
{ lng: 121.473416, lat: 31.230385 },
{ lng: 121.477451, lat: 31.232183 },
{ lng: 121.467923, lat: 31.227633 },
{ lng: 121.461744, lat: 31.228073 },
{ lng: 121.481656, lat: 31.23277 },
{ lng: 121.481828, lat: 31.231302 },
{ lng: 121.464662, lat: 31.227119 },
{ lng: 121.471829, lat: 31.229082 },
{ lng: 121.473159, lat: 31.231945 }
].map((v, i) => {
return new AMap.Marker({
position: new AMap.LngLat(v.lng, v.lat),
offset: new AMap.Pixel(0, 0),
content: '`<div class="container">1</div>`',
extData: { id: i }
})
})
const selectedIds = new Set()
const map = new AMap.Map("mapView", {
resizeEnable: true,
center: [121.47273, 31.231486],
zoom: 16
})
const cluster = new AMap.MarkerClusterer(map, [], {
gridSize: 80,
renderClusterMarker: _renderClusterMarker,
minClusterSize: 1,
zoomOnClick: false
})
function _renderClusterMarker(context) {
// console.log(context)
let isSelected = false
context.markers.forEach(v => {
if (selectedIds.has(v.getExtData().id)) {
isSelected = true
}
})
context.marker.setOffset(new AMap.Pixel(-20, -20))
if (isSelected) {
context.marker.setContent(`<div class="container selected">${context.count}</div>`)
} else {
context.marker.setContent(`<div class="container">${context.count}</div>`)
}
}
function setMarkers(markers, selectedIds) {
cluster.setMarkers(markers)
}
setMarkers(markers, selectedIds)
cluster.on('click', ev => {
// console.log(ev.markers)
selectedIds.clear()
ev.markers.forEach(v => selectedIds.add(v.getExtData().id))
setMarkers(markers, selectedIds)
})
map.on('click', ev => {
// console.log(ev)
if (selectedIds.size > 0) {
selectedIds.clear()
setMarkers(markers, selectedIds)
}
})
</script>
</body>
</html>