跳到主要内容
版本:9.3.0

聚类点信息获取

单击聚类点,获取原始信息,在控制台输出

show
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>聚类点信息获取</title>
<meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no"/>
<style>
body {
margin: 0;
padding: 0;
}

#map {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
}
</style>
<script src="https://delivery.mapmost.com/cdn/sdk/webgl/v9.3.0/mapmost-webgl-min.js"></script>
</head>
<body>
<div id="map"></div>
<script>
let map = new mapmost.Map({
container: 'map',
style: "<your style url>",
center: [120.72541613154851, 31.32271803927643],
zoom: 13,
doubleClickZoom:false, // 关闭双击放大
userId: '***', // 授权码
});

map.on('load', function () {

map.addSource("points", {
type: "geojson",
data: "../example_data/random_points.geojson",
cluster: true,
clusterMaxZoom: 14, // 聚集点的最大放大倍数。
clusterRadius: 50 // 对点进行聚类时每个聚类的半径(默认为50)。
});

// 聚类点
map.addLayer({
id: "clusters",
type: "circle",
source: "points",
filter: ["has", "point_count"],
paint: {
"circle-color": [
"step",
["get", "point_count"],
"#21984c",
50,
"#e27530",
120,
"#e61f16"
],
'circle-stroke-width': 6,
'circle-stroke-color': [
'step',
['get', 'point_count'],
'rgba(33,152,76,0.4)',
50,
'rgba(226,117,84,0.4)',
120,
'rgba(230,31,22,0.4)',
],
"circle-radius": [
"step",
["get", "point_count"],
10,
20,
20,
75,
25,
150,
30
],
}
});

// 单个点
map.addLayer({
id: "unclustered-point",
type: "circle",
source: "points",
filter: ["!", ["has", "point_count"]],
paint: {
"circle-color": "#46a5fe",
"circle-radius": 5,
}
});

// 数值标注层
map.addLayer({
id: "cluster-count",
type: "symbol",
source: "points",
filter: ["has", "point_count"],
layout: {
"text-field": "{point_count_abbreviated}",
"text-size": [
'step',
['get', 'point_count'],
14,
20,
16,
50,
18,
],
},
paint: {
"text-color": "#fff",
}
});

// 点击获取聚类点信息
map.on('click', 'clusters', function (e) {
let features = map.queryRenderedFeatures(e.point, {
layers: ['clusters']
});

let clusterId = features[0].properties.cluster_id;
let pointCount = features[0].properties.point_count;
let clusterSource = map.getSource('points');

clusterSource.getClusterLeaves(clusterId, pointCount, 0, function (error, features) {
// 在控制台输出
if(error){
console.log(error)
}else{
console.log('Cluster leaves:', features);
}
})
});

// 如果单击单个点
map.on('click', 'unclustered-point', function (e) {
console.log('one point:', e.features);
});

map.on('mouseenter', 'clusters', function () {
map.getCanvas().style.cursor = 'pointer';
});
map.on('mouseleave', 'clusters', function () {
map.getCanvas().style.cursor = '';
});
});

</script>
</body>
</html>