0%

高德地图点聚合的使用

项目中遇到了点聚合,并且点聚合样式和 Marker 样式都需要自定义

首先,只需在 marker 的 content 中加入自定义的 html 内容即可。

1
2
3
4
5
marker = new AMap.Marker({
position: lnglat,
content: '<div style="height: 24px; width: 24px; "><img style="width:60px;height:26px" src="marker.png"></div>',
offset: new AMap.Pixel(-25, -15),
})

然后将points批量加入到markers,并且可以添加一些属性到marker中

1
2
marker.data = points[i].data
marker.lnglat = points[i].lnglat

给marker添加事件

1
addEventHandler(marker);

添加marker最终代码为

1
2
3
4
5
6
7
8
9
10
11
for (var i = 0; i < points.length; i += 1) {
marker = new AMap.Marker({
position: points[i].lnglat,
content: '<div style="height: 24px; width: 24px; "><img style="width:60px;height:26px" src="marker.png"></div>',
offset: new AMap.Pixel(-25, -15),
})
marker.data = points[i].data
marker.lnglat = points[i].lnglat
addEventHandler(marker);
markers.push(marker);
}

marker的事件处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
function addEventHandler(marker) {
var infoWindow;
marker.on("mouseover", function (e) {
marker.setPosition(e.target.lnglat)
var info = []
info.push('<div class=\'markbox\'><p style="margin:0" class=\'input-item\'>data:' + e.target.data + '</p>')

infoWindow = new AMap.InfoWindow({
content: info.join(''), //使用默认信息窗体框样式,显示信息内容
offset: new AMap.Pixel(0, 0),
autoMove: false, //是否自动移动地图显示完整的InfoWindow
closeWhenClickMap: true // 点击地图是否关闭
})

infoWindow.open(map, e.target.lnglat)
})
marker.on('mouseout', function (e) {
infoWindow.close()
})
//点击marker
marker.on('click', function (e) {
// xxx
})
}
```

这样marker就创建完成了,但是如果marker数量过多,在地图中显示会很乱,所以需要用到点聚合

addCluster();
//添加聚合点
function addCluster() {
if (cluster) {
map.remove(cluster);
}
cluster = new AMap.MarkerClusterer(map, markers, {
gridSize: 200,
maxZoom: 14, // 最大zoom不再聚合
renderClusterMarker: _renderClusterMarker // 完全自定义样式
});
}

//这里可以完全自定义html和样式
var _renderClusterMarker = function (context) {
var div = document.createElement(‘div’);
var size = Math.round(30 + Math.pow(context.count / zwlCount, 1 / 5) * 20);
div.style.width = div.style.height = size / 2 + ‘px’;
div.innerHTML = ‘

‘ + context.count + ‘
‘;
div.style.lineHeight = size + ‘px’;
div.style.color = ‘#fff’;
div.style.fontSize = ‘14px’;
div.style.textAlign = ‘center’;
context.marker.setOffset(new AMap.Pixel(-size / 2, -size / 2));
context.marker.setContent(div)
};