uni-app 自带map组件(腾讯地图) 简单的聚合功能实现

<template>
<view class="content">
<map id="map" class="map" style="width: 100%;height: 100vh;" :show-location="true" :latitude="latitude" :longitude="longitude" @markertap="markertap"></map>
</view>
</template>
<script>
const img = '/static/map/location.png';
export default {
data() {
return {
latitude: 39.909,
longitude: 116.39742,
_mapContext:null,
}
},
onReady() {
this._mapContext = uni.createMapContext("map", this);
this._mapContext.initMarkerCluster({
enableDefaultStyle: false,
zoomOnClick: true,
gridSize: 60,
complete(res) {
console.log('initMarkerCluster', res)
}
});
this._mapContext.on("markerClusterCreate", (e) => {
const clusters = e.clusters
let clusterMarkers = []
clusters.forEach((cluster,index) => {
const { center,clusterId,markerIds } = cluster
let clusterObj = { clusterId,...center,width:0,height:0,iconPath:'',label:{
content:markerIds.length+'',
fontSize:16,
color:'#fff',
width:50,height:50,
bgColor:'#419afcD9',
borderRadius:25,
textAlign:'center',
anchorX:-10,
anchorY:-35
}}
clusterMarkers.push(clusterObj)
this._mapContext.addMarkers({
markers:clusterMarkers,
clear:false
})
});
});
this.addMarkers();
},
methods: {
addMarkers() {
const positions = []
for (let i = 0; i < 100; i++) {
positions.push({
id: i + 1,
latitude: 39.9 + Math.random() * 0.2 - 0.1,
longitude: 116.4 + Math.random() * 0.2 - 0.1,
})
}
const markers = []
positions.forEach((p, i) => {
markers.push(
Object.assign({},{
id: i + 1,
iconPath: img,
width: 50,
height: 50,
joinCluster: true
},p)
)
})
this._mapContext.addMarkers({
markers,
clear: false,
complete(res) {
console.log('addMarkers', res)
}
})
},
markertap(e) {
console.log(123131)
}
}
}
</script>
<style>
.content {
flex: 1;
}
.map {
flex: 1;
}
</style>