tooltip实现方式主要分两种:entity和div。
entity:基于cesium提供的entity接口
优点:地球放大、缩小或移动,位置也会跟着变化;显示灵活,无鼠标悬浮上面丢失焦点的bug
缺点:展示的信息不能是html格式,只能是文本;遮挡问题
div:基于悬浮的div控件
优点:展示的信息可以是html格式;无遮挡问题
缺点:地球放大、缩小或移动,位置不会跟着变化;有鼠标悬浮上面丢失焦点的bug
今天介绍基于entity方式:
//封装TooltipCesium对象
var TooltipCesium = (function () {
var isInit = false;
var viewer;
var labelEntity;
function _() { };
_.initTool = function (_viewer) {
if (isInit) { return; }
viewer = _viewer;
labelEntity = viewer.entities.add({
position: Cesium.Cartesian3.fromDegrees(0, 0),
label: {
text: '提示',
font: '15px sans-serif',
pixelOffset: new Cesium.Cartesian2(8, 8),//y大小根据行数和字体大小改变
horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
showBackground: true,
backgroundColor: new Cesium.Color(0.165, 0.165, 0.165, 1.0)
}
});
labelEntity.show = false;
isInit = true;
};
_.setVisible = function (visible) {
if (!isInit) { return; }
labelEntity.show = visible ? true : false;
};
_.showAt = function (position, message) {
if (!isInit) { return; }
if (position && message) {
labelEntity.show = true;
var cartesian = viewer.camera.pickEllipsoid(position, viewer.scene.globe.ellipsoid);//
if (cartesian) {
labelEntity.position = cartesian;
labelEntity.show = true;
labelEntity.label.text = message;
} else {
labelEntity.show = false;
}
}
};
_.showAtCartesian = function (cartesian, message) {
if (!isInit) { return; }
if (cartesian && message) {
labelEntity.show = true;
labelEntity.position = cartesian;
labelEntity.show = true;
labelEntity.label.text = message;
}
};
return _;
})();
var viewer = new Cesium.Viewer('cesiumContainer',{
baseLayerPicker:false,
imageryProvider: new Cesium.UrlTemplateImageryProvider({
url:'http://localhost:8080/xyz/Satellite_24459/{z}/{x}/{y}.jpg'
})
});
var scene = viewer.scene;
var handler = new Cesium.ScreenSpaceEventHandler(scene.canvas);
var ellipsoid = scene.globe.ellipsoid;
var cartesian = null;
TooltipCesium.initTool(viewer);
//监听鼠标单击事件
handler.setInputAction(function (movement) {
cartesian = viewer.camera.pickEllipsoid(movement.position, ellipsoid);
if (cartesian) {
TooltipCesium.showAt(movement.position, '要展示的信息');
// TooltipCesium.showAtCartesian(cartesian, '要展示的信息');
} else {
TooltipCesium.setVisible(false);
}
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);