提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
使用Cesium地图添加点位并且添加点击事件后,发现点击事件会调用多次,在查找中发现是因为调用接口点位多次添加并没有删除的问题导致的,因此在添加点位时要及时删除已经添加的点位和点击事件
一、添加点位和删除
添加点位和点位聚合的接口如下
var dataSource1 = new Cesium.CustomDataSource("dataSource1"); //自定义一个名为dataSource1的空数据集
var dataSourcePromise;
res.data.list.forEach((data) => {
var img_path = require('@/assets/images/location.png');
if (!data.longitude && !data.latitude) return;
dataSource1.entities.add(new Cesium.Entity({
position: Cesium.Cartesian3.fromDegrees(data.longitude, data.latitude), //从item对象获取经纬度
billboard: {
image: img_path,
horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
scale: 1, // 标注点icon缩放比例
width: 26, // 设置标注点icon的高和宽,单位默认时px
height: 36,
},
label: {
show: true, //是否显示标注点文本
scale: 0.6,
font: "normal 900 24px MicroSoft YaHei", //字体
fillColor: Cesium.Color.fromCssColorString("#3976bd"), //字体颜色
text: data.fileName, //从接口获取点的标记文本
pixelOffset: new Cesium.Cartesian2(0, -50), //文字显示的偏移量
horizontalOrigin: Cesium.HorizontalOrigin.CENTER, //水平居中
verticalOrigin: Cesium.VerticalOrigin.CENTER, //垂直居中
style: Cesium.LabelStyle.FILL,
showBackground: true, //设置文本背景
backgroundColor: Cesium.Color.fromCssColorString("#ffffff") //设置文本背景颜色,
},
dataId: data.id
}))
})
this.viewer.flyTo(dataSource1); //地图视角到点位处
//添加聚合功能
dataSourcePromise = this.viewer.dataSources.add(dataSource1);
dataSourcePromise.then(function (dataSource) {
const pixelRange = 100;
const minimumClusterSize = 2;
const enabled = true;
dataSource.clustering.enabled = enabled; //聚合开启
dataSource.clustering.pixelRange = pixelRange; //设置像素范围,以扩展显示边框
dataSource.clustering.minimumClusterSize = minimumClusterSize; //设置最小的聚合点数目,超过此数目才能聚合
// 添加监听函数
dataSource.clustering.clusterEvent.addEventListener(
function (clusteredEntities, cluster) {
// 关闭自带的显示聚合数量的标签
cluster.label.show = false;
cluster.billboard.show = true;
cluster.billboard.verticalOrigin = Cesium.VerticalOrigin.BOTTOM;
// 根据聚合数量的多少设置不同层级的图片以及大小
if (clusteredEntities.length >= 20) {
cluster.billboard.image = self.combineIconAndLabel(require('@/assets/images/poly_big.png'), clusteredEntities.length, 64);
cluster.billboard.width = 72;
cluster.billboard.height = 72;
} else {
cluster.billboard.image = self.combineIconAndLabel(require('@/assets/images/poly_little.png'), clusteredEntities.length, 64);
cluster.billboard.width = 40;
cluster.billboard.height = 40;
}
}
)
})
this.handlePointClick() //添加点击事件
标注点的点击事件
handlePointClick() {
let that = this;
that.handlerClick = new Cesium.ScreenSpaceEventHandler(that.viewer.scene.canvas);
that.handlerClick.setInputAction(function (click) {
let pick = that.viewer.scene.pick(click.position)
if (pick && pick.id) {
//点击后的操作
}
}, Cesium.ScreenSpaceEventType.LEFT_CLICK)
},
删除地图绘制的点
initMapPoints(){
this.viewer.entities.removeAll(); //删除地图上绘制的所有的点
this.viewer.dataSources.removeAll(); //删除地图上面的聚合点
if(this.handlerClick!=''){ //删除地图点的点击事件
this.handlerClick.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK)
}
},