坐标拾取功能:
1.鼠标左键点击地图,在该处使用红色圆点进行标记;
2.在标记点上方显示经纬度及海拔高度;
3.鼠标右键点击清除所有标记,并取消左键点击标记功能。
代码如下:
/**
* @description: 获取当前鼠标点击位置坐标
* @return {*}
*/
function getClickPoint(viewer) {
// 屏幕点击事件
var pointsCollection = []; // 标记点集合,方便后续将标记的点进行清除;
viewer.screenSpaceEventHandler.setInputAction((evt) => {
var ray = viewer.camera.getPickRay(evt.position);
var cartesian = viewer.scene.globe.pick(ray, viewer.scene);
if(Cesium.defined(cartesian)){
var cartographic = Cesium.Cartographic.fromCartesian(cartesian);
// console.log(cartesian, cartographic)
var lng = Cesium.Math.toDegrees(cartographic.longitude); // 经度值
var lat = Cesium.Math.toDegrees(cartographic.latitude); // 纬度值
var height = cartographic.height;
var entity = viewer.entities.add({
position: Cesium.Cartesian3.fromDegrees(lng, lat, height),
label: { //文字标签
text: 'Lon: '+lng.toFixed(5)+'\u00B0'+'\nLat: '+lat.toFixed(5)+'\u00B0'+'\nheight: '+height.toFixed(2)+'m',
font: '20px monospace', //15pt monospace
fillColor: Cesium.Color.BLACK, //文字颜色
scale: 1,
style: Cesium.LabelStyle.FILL,
pixelOffset: new Cesium.Cartesian2(-90, -30), //偏移量
showBackground: true,
backgroundColor: Cesium.Color.AQUA.withAlpha(1),
backgroundPadding: new Cesium.Cartesian2(17, 10),
horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
disableDepthTestDistance:Number.POSITIVE_INFINITY,
},
point:{
color:Cesium.Color.RED,
pixelSize:9,
outlineColor:Cesium.Color.ALICEBLUE,
outlineWidth:2,
disableDepthTestDistance:Number.POSITIVE_INFINITY,
},
})
pointsCollection.push(entity);
}
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
viewer.screenSpaceEventHandler.setInputAction(function(){
// 删除标记点
pointsCollection.forEach(function (item) {
if (item instanceof Cesium.Entity) {
viewer.entities.remove(item);
}
})
// 清除左键点击标记事件
viewer.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
}, Cesium.ScreenSpaceEventType.RIGHT_CLICK)
}