import * as Cesium from "cesium/Cesium.js";
import config from './config'
import {$Params} from "./params";
import {rgbaToCesiumColor} from './transform.js'
import {initLoadModel} from './init'
import { infoWindow } from './infoWindow'
export const MyCesium = {
viewer: undefined,
handler: undefined,
imageryProvider: new Cesium.UrlTemplateImageryProvider({
url: config.mapUrl.tianditu,
credit: new Cesium.Credit("天地图全球影像服务"),
subdomains: ["t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7"],
tilingScheme: new Cesium.WebMercatorTilingScheme(),
maximumLevel: 18,
enablePickFeatures: false
}),
curentEntity:null,
isDraw: false,
curLabelEntity: null,
highlightFace: undefined,
model: null,
init(ele) {
var tipOverlay = document.createElement('div');
if (this.viewer) return false
this.viewer = new Cesium.Viewer(ele, {
navigationHelpButton: false,
sceneModePicker: false,
navigationInstructionsInitiallyVisible: false,
animation: false,
fullscreenButton: false,
timeline: false,
vrButton: false,
geocoder: false,
infoBox: false,
homeButton: false,
selectionIndicator: true,
imageryProvider: this.imageryProvider,
baseLayerPicker: false,
shouldAnimate: true,
});
this.viewer.container.appendChild(tipOverlay)
this.viewer._cesiumWidget._creditContainer.style.display = "none";
if (this.viewer.sceneModePickviewer) {
this.viewer.sceneModePicker.viewModel.tooltip3D = "三维";
this.viewer.sceneModePicker.viewModel.tooltip2D = "二维";
this.viewer.sceneModePicker.viewModel.tooltipColumbusView = "哥伦布视图";
}
this.viewer.scene.globe.depthTestAgainstTerrain = false;
this.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);
this.viewer.screenSpaceEventHandler.setInputAction(function () { }, Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
infoWindow({ viewer: this.viewer }).openWindow()
},
morphSwitch(mode) {
let morphTo = 'morphTo' + mode
this.viewer.scene[morphTo](0);
this.viewer.scene.primitives.show = mode == '2D' ? false : true;
this.viewer.imageryLayers.removeAll();
let imageArr = {
'2D' : [
{
url: "https://{s}.tianditu.gov.cn/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=天地图key",
credit: new Cesium.Credit("天地图全球影像服务"),
subdomains: ["t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7"],
tilingScheme: new Cesium.WebMercatorTilingScheme(),
maximumLevel: 18,
enablePickFeatures: false,
show: false
},
{
url: "https://{s}.tianditu.gov.cn/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=天地图key",
credit: new Cesium.Credit("天地图全球影像服务"),
subdomains: ["t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7"],
tilingScheme: new Cesium.WebMercatorTilingScheme(),
maximumLevel: 18,
enablePickFeatures: false,
}
],
'3D': [{
url: "https://{s}.tianditu.gov.cn/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=天地图key",
credit: new Cesium.Credit("天地图全球影像服务"),
subdomains: ["t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7"],
tilingScheme: new Cesium.WebMercatorTilingScheme(),
maximumLevel: 18,
enablePickFeatures: false,
}]
}
imageArr[mode].forEach(item => {
let imagery = new Cesium.UrlTemplateImageryProvider(item)
this.viewer.imageryLayers.addImageryProvider(imagery);
})
},
hightlightFeature(entity, tag, id) {
if(!entity && tag) entity = this.lookEntityById(tag, id, true)
const highlighter = () => {
var temp = new Array();
function linehHghtlight(nameId) {
var exists = temp.indexOf(nameId);
if (exists <= -1) {
temp.push(nameId);
} else {
temp.splice(exists, 1);
}
}
if (this.highlightFace) {
this.highlightFace.material = this.highlightFace.material0;
}
entity.polygon.material0 = entity.polygon.material;
entity.polygon.material = Cesium.Color.WHITE;
this.highlightFace = entity.polygon;
if (typeof (entity) != "undefined")
var id = entity.id;
linehHghtlight(id);
}
const removeHighLighter = () => {
this.highlightFace.material = this.curentEntity.polygon.material0
}
return {
add: highlighter,
remove: removeHighLighter,
}
},
showImageLayer() {
this.viewer.imageryLayers._layers[0].show = !this.viewer.imageryLayers._layers[0].show
},
getBillboardProperty(tag, item) {
let imgObj = {
1: {
onLine: require('../../assets/device/cameraOnline.png'),
offLine: require('../../assets/device/cameraOffline.png'),
},
2: {
onLine: require('../../assets/device/radar.png'),
offLine: require('../../assets/device/radar_off.png'),
},
3: {
onLine: require('../../assets/device/AIS.png'),
offLine: require('../../assets/device/AIS_off.png'),
},
4: {
onLine: require('../../assets/device/waterQualityOnline.png'),
offLine: require('../../assets/device/waterQualityOffline.png'),
}
}
let imgUrl = item.isOnline == 1? imgObj[item.iotDeviceType].onLine : imgObj[item.iotDeviceType].offLine
let obj = {
image: imgUrl,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
width: 20,
height: 25,
clampToGround: true,
classificationType: Cesium.ClassificationType.CESIUM_3D_TILE,
verticalOrigin : Cesium.VerticalOrigin.BOTTOM
}
return obj
},
createBillboard(tag, item) {
let billboardProperty = this.getBillboardProperty(tag, item)
let billboards = this.dataSource.entities.add(new Cesium.Entity({
id: item.id,
position: Cesium.Cartesian3.fromDegrees(item.lon, item.lat, item.height ? item.height : 0),
billboard: billboardProperty,
type: 'billboard',
tag: tag,
label: {
text: item.iotDeviceName,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
font: '10px sans-serif',
fillColor: Cesium.Color.WHITE,
backgroundColor: Cesium.Color.AQUA,
showBackground: false,
scale: 1.0,
style: Cesium.LabelStyle.FILL_AND_OUTLINE,
verticalOrigin: Cesium.VerticalOrigin.CENTER,
horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
pixelOffset: new Cesium.Cartesian2(0, 0),
show: true,
},
description: {...item, ...{tag: tag}},
}));
return billboards;
},
createBillboardLabel(tag, item) {
let lal = item.lal;
let imgUrl = require('../../assets/images/marker-water.png')
let label = this.dataSource.entities.add(new Cesium.Entity({
position: Cesium.Cartesian3.fromDegrees(item.lon, item.lat, item.height ? item.height : 0),
billboard: {
image: imgUrl,
width: 50,
height: 60,
clampToGround: true,
classificationType: Cesium.ClassificationType.CESIUM_3D_TILE,
verticalOrigin : Cesium.VerticalOrigin.BOTTOM,
},
id: item.id,
label: {
text : 'PH:7.4;水温:21.5℃;油污:无',
color : Cesium.Color.fromCssColorString('#fff'),
font : '15px sans-serif',
horizontalOrigin: Cesium.HorizontalOrigin.TOP,
verticalOrigin: Cesium.VerticalOrigin.TOP,
pixelOffset: new Cesium.Cartesian2(0, -90),
},
type: 'label',
tag: tag,
description: {...item, ...{tag: tag}},
}))
return label;
},
createPoint(tag, item) {
let lal = item && item.lal && item.lal.length > 0 ? item.lal[0] : null;
let pointGeometry = this.dataSource.entities.add(new Cesium.Entity({
id: item.id,
position: Cesium.Cartesian3.fromDegrees(lal[0] * 1, lal[1] *1,item.height),
point: {
color: Cesium.Color.LIMEGREEN ,
pixelSize: 0,
outlineColor: Cesium.Color.AQUA.withAlpha(0.4),
outlineWidth: 0,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
},
type: 'point',
tag: tag,
}));
return pointGeometry;
},
createPolyline(tag, item) {
let defaultDrawStyle = {...$Params.PolyLineStyle}
if(item.lineColor) defaultDrawStyle.material = rgbaToCesiumColor(item.lineColor)
if(item.lineWidth) defaultDrawStyle.width = item.lineWidth * 1
if(item && item.attrs && item.attrs.hasOwnProperty("css")) {
let attrs = item.attrs
if(attrs.css) {
defaultDrawStyle.material = rgbaToCesiumColor(attrs.css.lineColor)
defaultDrawStyle.width = attrs.css.lineWidth
}
}
let lineStyle = {...defaultDrawStyle, ...{positions: Cesium.Cartesian3.fromDegreesArray(item.lal)}}
let polylineGeometry = this.dataSource.entities.add(new Cesium.Entity({
id: item.id,
polyline: lineStyle,
type: 'line',
tag: tag,
description: item
}))
return polylineGeometry
},
createDrawPolygon(tag, item) {
console.log(item, 'createDrawPolygon')
let defaultDrawStyle = {...$Params.PolygonStyle};
if(item.fillColor) defaultDrawStyle.material = rgbaToCesiumColor(item.fillColor)
if(item.lineColor) defaultDrawStyle.outlineColor = rgbaToCesiumColor(item.lineColor)
if(item.lineWidth) defaultDrawStyle.outlineWidth = item.lineWidth * 1
let polygonStyle = {...defaultDrawStyle, ...{hierarchy: new Cesium.Cartesian3.fromDegreesArray(item.lal)}}
let polygonGeometry = this.dataSource.entities.add(
{
id: item.id,
position: Cesium.Cartesian3.fromDegrees(item.lal[0] * 1, item.lal[1] *1, 0),
polygon: polygonStyle,
type: 'polygon',
tag: tag,
description: item,
label: {
text: item.name,
font : '10px sans-serif',
disableDepthTestDistance: Number.POSITIVE_INFINITY,
fillColor: Cesium.Color.WHITE,
backgroundColor: new Cesium.Color(0.0, 0.0, 0.0, 0.0),
showBackground: true,
verticalOrigin: Cesium.VerticalOrigin.CENTER,
horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
pixelOffset: new Cesium.Cartesian2(25, 20),
show: true
},
},
)
return polygonGeometry;
},
addEntitysCollection(tag, data) {
this.dataSource = this.createDataSourceByTag(tag);
for (var i = 0; i < data.length; i++) {
if (data[i].type == 1) {
this.createBillboard(tag, data[i])
} else if (data[i].type == 2) {
this.createPolyline(tag, data[i])
} else if (data[i].type == 3) {
this.createDrawPolygon(tag, data[i])
} else if (data[i].type == 4) {
this.createBillboardLabel(tag, data[i])
}
}
},
addDeviceEntitysCollection(tag, data) {
this.dataSource = this.createDataSourceByTag(tag);
for (var i = 0; i < data.length; i++) {
this.createBillboard(tag, data[i])
}
},
lookEntityById(tag, id, isFllow) {
let entity = null
let item = this.viewer.dataSources.getByName(tag)
if(item.length > 0) {
let items = item[0]
entity = items.entities.getById(id);
}
if(isFllow && entity) {
this.zoomToEntity(entity)
this.selectEntity(entity)
}
return entity
},
zoomToEntity(entity) {
this.viewer.zoomTo(entity)
},
cartesian3ToDegrees(cartesian3) {
let ellipsoid = this.viewer.scene.globe.ellipsoid;
let cartographic = ellipsoid.cartesianToCartographic(cartesian3);
let lat = Cesium.Math.toDegrees(cartographic.latitude);
let lng = Cesium.Math.toDegrees(cartographic.longitude);
let alt = cartographic.height;
return [lng, lat]
},
createDataSourceByTag(tag) {
let _dataSource = new Cesium.CustomDataSource(tag)
this.viewer.dataSources.add(_dataSource);
return _dataSource
},
getDataSourceByTag(tag) {
this
},
isExistsDataSourceByTag(tag) {
let dataSource = this.viewer.dataSources.getByName(tag)
if(dataSource.length > 0) return true
else return false
},
isShowEntityCollection(tag) {
this.viewer.dataSources._dataSources.forEach(item => {
if (item.name == tag) item.show = !item.show
})
},
removeDataSources() {
this.viewer.dataSources.removeAll()
},
removeEntities() {
this.viewer.entities.removeAll()
},
removeEntityById(tag, id) {
let item = this.viewer.dataSources.getByName(tag)[0]
item.entities.removeById(id)
},
defined(value) {
return value !== undefined && value !== null;
},
selectEntity(value) {
if (this.viewer.selectedEntity !== value) {
this.viewer.selectedEntity = value;
let selectionIndicatorViewModel = this.defined(this.viewer.selectionIndicator) ? this.viewer.selectionIndicator.viewModel : undefined;
if (this.defined(value)) {
if (this.defined(selectionIndicatorViewModel)) {
selectionIndicatorViewModel.animateAppear();
setTimeout(() => {
if(this.viewer.selectionIndicator) {
let svg = this.viewer.selectionIndicator.viewModel.selectionIndicatorElement.getElementsByTagName('svg:svg')[0];
svg.style.display = 'block'
svg.style.marginTop = '-20px'
}
}, 100)
}
} else if (this.defined(selectionIndicatorViewModel)) {
selectionIndicatorViewModel.animateDepart();
}
this.viewer.selectedEntityChanged.raiseEvent(value);
}
},
lookEntity(tag, id) {
let item = this.viewer.dataSources.getByName(tag)
console.log('item', item)
if(item.length > 0) {
let items = item[0]
let currentEntity = items.entities.getById(id);
console.log('currentEntity', currentEntity)
let postions;
var model2;
let centerPoint1 = null
if(currentEntity) {
if(currentEntity.position){
model2=new Cesium.Entity({
position:currentEntity.position._value
})
}else if(currentEntity.polygon || currentEntity.polyline){
if(currentEntity.polygon) postions = currentEntity.polygon.hierarchy._value.positions
else postions = currentEntity.polyline.positions.getValue();
let newPosttions=[];
postions.forEach(item=>{
let pp = this.cartesian3ToDegrees(item);
let p ={lng:pp[0],lat:pp[1]};
newPosttions.push(p);
})
let centerPoint = this.calculateCenterPoint(newPosttions);
centerPoint1 = centerPoint
model2=new Cesium.Entity({
position:Cesium.Cartesian3.fromDegrees(centerPoint[0],centerPoint[1])
})
}
this.viewer.zoomTo(currentEntity,
{
heading: Cesium.Math.toRadians(20),
pitch: Cesium.Math.toRadians(-90),
range: 500,
}
).then(res => {
})
this.selectEntity(model2);
}
}
},
calculateCenterPoint(pointArray){
const sortedLongitudeArray=pointArray.map(item=>Number(item.lon)).sort();
const sortedLatitudeArray=pointArray.map(item=>Number(item.lat)).sort();
const centerLongitude=((sortedLongitudeArray[0]+sortedLongitudeArray[sortedLongitudeArray.length-1])/2);
const centerLatitude=((sortedLatitudeArray[0]+sortedLatitudeArray[sortedLatitudeArray.length-1])/2);
return [centerLongitude,centerLatitude];
},
removeDataSource(tag) {
this.viewer.dataSources._dataSources.forEach(item => {
if (item.name == tag) {
this.viewer.dataSources.remove(item)
}
})
},
isShowSelectionIndicator(bool) {
let svg = this.viewer.selectionIndicator.viewModel.selectionIndicatorElement.getElementsByTagName('svg:svg')[0];
svg.style.display = bool ? 'block' : 'none'
},
createPointee() {
this.viewer.entities.add({
name: '点',
type: "point",
position: Cesium.Cartesian3.fromDegrees(121.1783503372873, 27.8410203244728),
point: {
pixelSize: 5,
color: Cesium.Color.RED,
outlineColor: Cesium.Color.WHITE,
outlineWidth: 2,
},
description: {
name: 'gggg',
ip: '52.19.98.23',
state: '888',
}
})
},
createPolygong() {
let ss = this.viewer.entities.add({
name: '面',
type: "polygon",
polygon: {
hierarchy: Cesium.Cartesian3.fromDegreesArray([121.17672770105298, 27.84266792430584, 121.17380767587856, 27.84509403528806,
121.17244173260276, 27.84350967632169, 121.17587752187254, 27.840680559624595
]),
outline: true,
outlineWidth: 3,
clampToGround: true,
height: 1,
material: Cesium.Color.AQUA.withAlpha(0.4),
},
description: {
name: 'gggg',
ip: '52.19.98.23',
state: '888',
}
})
this.viewer.zoomTo(ss);
},
createPolygongWidthHeight() {
let ss = this.viewer.entities.add({
name: '面',
type: "polygon",
polygon: {
hierarchy: Cesium.Cartesian3.fromDegreesArrayHeights([121.17672770105298, 27.84266792430584, 200, 121.17380767587856, 27.84509403528806, 1000,
121.17244173260276, 27.84350967632169, 0,121.17587752187254, 27.840680559624595, 0
]),
perPositionHeight : true,
outline: true,
outlineWidth: 3,
height: 3000,
clampToGround: false,
material: Cesium.Color.AQUA.withAlpha(0.4),
},
description: {
name: 'gggg',
ip: '52.19.98.23',
state: '888',
}
})
this.viewer.zoomTo(ss);
},
createBillboardss() {
this.viewer.entities.add({
name: '广告牌',
type: "billboard",
position: Cesium.Cartesian3.fromDegrees(121.18059520326415, 27.840770748596473),
billboard: {
image: require('../../assets/images/marker.png'),
width: 30,
height: 40,
},
description: {
name: "广告牌",
id: 6666,
tag: "VideoMonitor",
channel: 888
}
})
},
createPolyliness() {
this.viewer.entities.add({
name: '广告牌',
type: "polyline",
polyline: {
material: new Cesium.PolylineDashMaterialProperty({
color: Cesium.Color.ORANGE,
dashLength: 8.0
}),
classificationType: Cesium.ClassificationType.BOTH,
height: 10,
width: 5,
positions: Cesium.Cartesian3.fromDegreesArray([121.17568292666387, 27.844761330195997, 121.17682424181234, 27.843636369864367])
},
})
},
}