Browse Source

1.修改window.属性

2.抽离EarthComp.vue
3.谨防BUG
master
DIAMOND 12 months ago
parent
commit
e9da899a13
  1. 1
      src/shims-vue.d.ts
  2. 7
      src/store/modules/earthMap.ts
  3. 70
      src/utils/earthMap/clone.ts
  4. 43
      src/utils/earthMap/createRealTimeObj.ts
  5. 37
      src/utils/earthMap/earth.ts
  6. 2
      src/utils/earthMap/earthDraw.ts
  7. 220
      src/utils/earthMap/getAllModelInfo.ts
  8. 165
      src/utils/earthMap/getLabelInfo.ts
  9. 2
      src/utils/earthMap/getLineInfo.ts
  10. 48
      src/utils/earthMap/getPatrolRouteInfo.ts
  11. 2
      src/utils/earthMap/guid.ts
  12. 10
      src/utils/earthMap/handleNodeType.ts
  13. 4
      src/utils/earthMap/keyControlInit.ts
  14. 437
      src/utils/earthMap/listenMouseHandler.ts
  15. 8
      src/utils/earthMap/listenMouseHandlerSence.ts
  16. 2
      src/utils/earthMap/radarEntity.ts
  17. 918
      src/utils/earthMap/sceneTreePopContextMenu.ts
  18. 36
      src/utils/earthMap/setIconByRef.ts
  19. 225
      src/utils/earthMap/setLabelStatus.ts
  20. 74
      src/utils/earthMap/websocket.ts
  21. 2832
      src/views/earthMap/edit/EarthComp.vue

1
src/shims-vue.d.ts

@ -11,6 +11,7 @@ declare global {
d3kit: any;
$earth: any;
$uia: any;
$viewer: any;
_CONFIG: any;
$flyTo: any;
guid: any;

7
src/store/modules/earthMap.ts

@ -24,8 +24,13 @@ export const useEarthMapStore = defineStore({
///////////////////////
cameraData: <any>{},//请求的电线杆数据
nodeConfigByRef: new Map(),// 区域节点By Ref划分
nodeCheckedByRef: new Map(),//
statusByNodeId: new Map(),//
areaByNodeId: new Map(),
hostDeviceMapById: new Map(),//获取主机信息
alarmInfoMap: new Map(),
radarAlarmDataMap: new Map(),
imgByRef: new Map(),
}),
getters: {

70
src/utils/earthMap/clone.ts

@ -0,0 +1,70 @@
/**
*
* EarthComp.vue
*/
export function cloneModel(modelObject) {
if (modelObject.czmObject.xbsjType === 'Model') {
const modelConfig = {
ref: '',
name: modelObject.name,
czmObject: {
name: modelObject.czmObject.name,
xbsjType: modelObject.czmObject.xbsjType,
url: modelObject.czmObject.url,
// "color": [0.52, 0.6, 0.58, 1],
minimumPixelSize: modelObject.czmObject.minimumPixelSize,
// maximumScale: 0.02,
scale: modelObject.czmObject.scale,
xbsjScale: [...modelObject.czmObject.xbsjScale],
xbsjPosition: [...modelObject.czmObject.xbsjPosition],
xbsjRotation: [...modelObject.czmObject.xbsjRotation],
viewDistance: 150,
distanceDisplayCondition: [1.0, 30000.0],
},
};
const index = modelObject.parent.children.push(modelConfig);
return index;
// const model = new window.XE.Obj.Model(window.$earth)
// model.xbsjFromJSON(modelConfig)
// const leaf = new window.XE.SceneTree.Leaf(model)
// window.$earth.sceneTree.root.push(leaf)
} else {
const objConfig3 = {
ref: '',
name: modelObject.name,
czmObject: {
customProp: modelObject.czmObject.customProp,
name: modelObject.czmObject.name,
xbsjType: modelObject.czmObject.xbsjType,
imageUrl: modelObject.czmObject.imageUrl,
position: [...modelObject.czmObject.position],
scale: modelObject.czmObject.scale,
pinBuilder: {
extText: modelObject.czmObject.pinBuilder.extText,
extTextFont: '30px 楷体',
extTextPixelOffset: [30, -20],
fillColor: [1, 1, 1, 0.9],
outlineColor: [0, 0, 0, 0.9],
},
far: 1073741824,
},
};
const index = modelObject.parent.children.push(objConfig3);
return index;
}
// return model
}
export function cloneShamNode(oldRef, id, title) {
const shamNode = window.$earth.sceneTree.$refs['node_' + oldRef];
const newShamNode = {
ref: 'node_' + id,
title: title,
expand: false,
children: [],
};
// that.currentModel = response.result
shamNode.parent.children.push(newShamNode);
}

43
src/utils/earthMap/createRealTimeObj.ts

@ -0,0 +1,43 @@
/**
* 线
* EarthComp.vue
*/
import getAllModelInfo from '@/utils/earthMap/getAllModelInfo';
import getPatrolRouteInfo from '@/utils/earthMap/getPatrolRouteInfo';
export default async function createRealTimeObj(earthUI = null) {
let models = {
expand: true,
title: '地图实况',
children: [
{
expand: false,
title: '巡逻路线',
children: [],
},
{
expand: false,
title: '执勤巡逻',
children: [],
},
{
expand: false,
title: '预警/报警',
children: [],
},
{
expand: false,
title: 'AIS',
children: [],
},
],
};
try {
await getAllModelInfo(models);
await getPatrolRouteInfo(models);
//添加对象到场景树
// window.$earth.sceneTree.root.children.push(models);
window.$earth.sceneTree.root.children.splice(1, 0, models);
} catch (e) {
console.log(e);
}
}

37
src/utils/earthMap/earth.ts

@ -68,6 +68,39 @@ function setBimStyle(bim: unknown,
},
});
}
// 根据经纬度获取高度
async function getHeigthByLonLat(lon = 88.8296258, lat = 27.4061859) {
var positions = [window.Cesium.Cartographic.fromDegrees(lon, lat)];
// var promise = Cesium.sampleTerrain(this._viewer.terrainProvider, 13, positions);
var promise = window.Cesium.sampleTerrainMostDetailed(window.$viewer.terrainProvider, positions);
return new Promise((resolve, reject) => {
window.Cesium.when(promise, function (updatedPositions) {
// updatedPositions[0].height ? updatedPositions[0].height : 0;
resolve(updatedPositions);
});
});
/* var terCartographic = new Cesium.Cartographic(1.5503694435245020004000376611976, 0.47832817936864542131039019315313, 0)
var terHigh = this._viewer.scene.globe.getHeight(terCartographic);
return terHigh; */
}
function getRandomArr(arr, count) {
//从数组随机抽取元素
var shuffled = arr.slice(0),
i = arr.length,
min = i - count,
temp,
index;
while (i-- > min) {
//打乱数组
index = Math.floor((i + 1) * Math.random());
temp = shuffled[index];
shuffled[index] = shuffled[i];
shuffled[i] = temp;
}
return shuffled.slice(min);
}
export default {
degreeToRadianInLngLatHeight,
@ -76,7 +109,9 @@ export default {
radianToDegree,
getDistance,
setBimStyle,
getHeigthByLonLat,
getRandomArr
}
export{
export {
radianToDegreeInLngLatHeight
}

2
src/utils/earthMap/earthDraw.ts

@ -25,6 +25,8 @@ const earthUI = window.$uia // 获取地图ui对象
//绘画图形初始化
export async function drawInit() {
console.log("加载绘画资源");
// console.log("sceneId",userStore.userInfo?.sceneId);
/**
* listBySceneId SceneId以及SceneId为空的列表

220
src/utils/earthMap/getAllModelInfo.ts

@ -0,0 +1,220 @@
/**
* EarthComp.vue
*/
import { defHttp } from '/@/utils/http/axios';
import { useUserStore } from '/@/store/modules/user';
import { useEarthMapStore } from '/@/store/modules/earthMap';
import { earthMapUrl } from '@/api/earth/earthMap'
import earthUtils from '@/utils/earthMap/earth';
let userStore = useUserStore();
let store = useEarthMapStore();
export default function getAllModelInfo(models) {
return new Promise((resolve, reject) => {
//模型位置
defHttp.get({ url: earthMapUrl.queryAllModelInfo }, { isTransformResponse: false }).then(async (res) => {
if (res.success) {
res.result.forEach((data, index) => {
let childrenConfig: any = {},
objConfig: any = {},
pathConfig: any = {},
viewshedConfig: any = {},
pinConfig: any = {};
let positions: any = [],
rotations: any = [];
switch (data.modelType) {
case 1: //无人机
childrenConfig = {
expand: false,
title: '无人机_' + (index + 1) + '号',
children: [],
};
objConfig = {
ref: data.eventSerialNum,
czmObject: {
name: '无人机',
xbsjType: 'Model',
url: window._CONFIG['staticDomainURL'] + '/uav.gltf',
minimumPixelSize: 1000,
maximumScale: 20,
xbsjPosition: earthUtils.degreeToRadianInLngLatHeight(data.lon, data.lat, data.height),
distanceDisplayCondition: [10.0, 25000.0],
},
};
childrenConfig.children.push(objConfig);
// 加载视域
viewshedConfig = {
ref: 'viewshed_' + data.eventSerialNum,
czmObject: {
xbsjType: 'Viewshed',
name: '视域',
position: earthUtils.degreeToRadianInLngLatHeight(data.lon, data.lat, data.height),
rotation: earthUtils.degreeToRadianInLngLatHeight(data.yaw, data.pitch, data.roll),
near: 1.0,
far: 1500,
enabled: false,
show: false,
},
};
childrenConfig.children.push(viewshedConfig);
//加载历史轨迹
data.msModelTrajectoryList.forEach((data, index) => {
positions.push(earthUtils.degreeToRadianInLngLatHeight(data.lon, data.lat, data.height));
rotations.push(earthUtils.degreeToRadianInLngLatHeight(data.yaw, data.pitch, data.roll));
});
pathConfig = {
ref: 'path_' + data.eventSerialNum,
czmObject: {
xbsjType: 'Path',
name: '轨迹',
positions: positions,
rotations: rotations,
enabled: false,
show: true,
loop: false,
showDirection: false,
playing: true,
loopPlay: true,
alwaysAlongThePath: true,
currentSpeed: 30,
},
};
childrenConfig.children.push(pathConfig);
/* //
pinConfig = {
"ref": "pin_" + data.eventSerialNum,
"czmObject": {
"xbsjType": "Pin",
"name": "当前位置",
"position": earthUtils.degreeToRadianInLngLatHeight(data.lon, data.lat, data.height),
"evalString": "const width = 430;\nconst height = 70;\nfunction createLabelCanvas(p) {\n if (p._labelDiv) {\n p._earth.czm.viewer.container.removeChild(p._labelDiv);\n p._labelDiv = undefined;\n }\n const labelDiv = document.createElement('div');\n labelDiv.style = 'width:'+width+'px;height: '+height+'px;position: absolute; pointer-events: none;'\n\n p._earth.czm.viewer.container.appendChild(labelDiv);\n p._labelDiv = labelDiv;\n\n var dis = XE.MVVM.watch(() => {\n labelDiv.style.display = p.enabled ? 'block' : 'none';\n });\n\n p.disposers.push(() => {\n if (p._labelDiv) {\n p._earth.czm.viewer.container.removeChild(p._labelDiv);\n p._labelDiv = undefined;\n }\n dis();\n });\n\n const labelCanvas = document.createElement('canvas');\n labelCanvas.style = 'width: 100%;height: 100%;';\n\n labelCanvas.width = width;\n labelCanvas.height = height;\n labelDiv.appendChild(labelCanvas);\n return labelCanvas;\n}\n\nfunction createDrawFunc(p) {\n const labelCanvas = createLabelCanvas(p);\n const ctx = labelCanvas.getContext('2d');\n\n function draw(w) {\n ctx.clearRect(0, 0, width, height);\n\n ctx.save();\n ctx.lineWidth = 2;\n ctx.strokeStyle = 'rgb(31, 255,255)';\n ctx.beginPath();\n ctx.moveTo(width, height);\n ctx.lineTo(width-height, 22);\n ctx.lineTo(0, 22);\n ctx.stroke();\n ctx.restore();\n ctx.font = \"15px console\"; \n ctx.fillStyle = 'rgb(255, 255, 0)';\n ctx.fillText('" +
"经度:" + data.lon + "/" + "纬度:" + data.lat + "/" + "高度:" + data.height + "', 0, 20);\n ctx.restore();\n }\n\n p._dDraw = draw;\n}\n\ncreateDrawFunc(p);\n\nlet d = 0;\nlet c = 0;\np._dDraw(c);\nconst preUpdateListener = p._earth.czm.scene.preUpdate.addEventListener(() => {\n if (d !== c) {\n c += (d - c) * 0.1;\n if (Math.abs(c - d) < 0.1) {\n c = d;\n }\n p._dDraw(c);\n }\n});\np.disposers.push(() => preUpdateListener && preUpdateListener());\n\nconst container = p._earth.czm.viewer.container;\nconst unwatch = XE.MVVM.watch(() => [...p.winPos], winPos => {\n if (p._labelDiv) {\n p._labelDiv.style.left = (winPos[0] - p._labelDiv.clientWidth) + 'px';\n p._labelDiv.style.bottom = winPos[3]+'px';\n } \n});\np.disposers.push(() => {\n unwatch && unwatch();\n});",
"isDivImage": true,
"pinBuilder": {},
"far": 25000
}
};
childrenConfig.children.push(pinConfig); */
//加入树
models.children[1].children.push(childrenConfig);
break;
case 2: //执勤人员
childrenConfig = {
expand: false,
title: '执勤人员_' + (index + 1) + '号',
children: [],
};
objConfig = {
ref: data.eventSerialNum,
czmObject: {
xbsjType: 'GroundImage',
name: '执勤人员',
playing: true,
width: 90,
height: 90,
position: earthUtils.degreeToRadianInLngLatHeight(data.lon, data.lat, 0),
imageUrls: [window._CONFIG['staticDomainURL'] + '/xunluo_point1.png', window._CONFIG['staticDomainURL'] + '/xunluo_point2.png'],
},
};
childrenConfig.children.push(objConfig);
//加载历史轨迹
data.msModelTrajectoryList.forEach((data, index) => {
positions.push(earthUtils.degreeToRadianInLngLatHeight(data.lon, data.lat, data.height));
rotations.push(earthUtils.degreeToRadianInLngLatHeight(data.yaw, data.pitch, data.roll));
});
pathConfig = {
ref: 'path_' + data.eventSerialNum,
czmObject: {
xbsjType: 'Path',
name: '轨迹',
positions: positions,
rotations: rotations,
enabled: false,
show: true,
loop: false,
showDirection: false,
playing: true,
loopPlay: true,
alwaysAlongThePath: true,
currentSpeed: 30,
},
};
childrenConfig.children.push(pathConfig);
//加入树
models.children[1].children.push(childrenConfig);
break;
case 3: //可疑人员
childrenConfig = {
expand: false,
title: '可疑人员_' + (index + 1) + '号',
children: [],
};
objConfig = {
ref: data.eventSerialNum,
czmObject: {
xbsjType: 'GroundImage',
name: '可疑人员',
playing: true,
width: 90,
height: 90,
position: earthUtils.degreeToRadianInLngLatHeight(data.lon, data.lat, 0),
imageUrls: [window._CONFIG['staticDomainURL'] + '/keyi_point1.png', window._CONFIG['staticDomainURL'] + '/keyi_point2.png'],
},
};
childrenConfig.children.push(objConfig);
//加载历史轨迹
data.msModelTrajectoryList.forEach((data, index) => {
positions.push(earthUtils.degreeToRadianInLngLatHeight(data.lon, data.lat, data.height));
rotations.push(earthUtils.degreeToRadianInLngLatHeight(data.yaw, data.pitch, data.roll));
});
pathConfig = {
ref: 'path_' + data.eventSerialNum,
czmObject: {
xbsjType: 'Path',
name: '轨迹',
positions: positions,
rotations: rotations,
enabled: false,
show: true,
loop: false,
showDirection: false,
playing: true,
loopPlay: true,
alwaysAlongThePath: true,
currentSpeed: 30,
},
};
childrenConfig.children.push(pathConfig);
//加入树
models.children[2].children.push(childrenConfig);
break;
case 11: //传感器
objConfig = {
ref: data.eventSerialNum,
czmObject: {
name: data.eventSerialNum,
xbsjType: 'Model',
url: window._CONFIG['staticDomainURL'] + '/zalan.gltf',
minimumPixelSize: 1000,
maximumScale: 0.01,
// xbsjPosition: [window.Cesium.Math.toRadians(data.lon), window.Cesium.Math.toRadians(data.lat), data.height],
xbsjPosition: earthUtils.degreeToRadianInLngLatHeight(data.lon, data.lat, data.height),
xbsjRotation: earthUtils.degreeToRadianInLngLatHeight(data.yaw, data.pitch, data.roll),
distanceDisplayCondition: [10.0, 25000.0],
customProp: data.eventSerialNum,
color: [0.08235294117647059, 1, 0, 1],
luminanceAtZenith: 2,
},
};
//加入树
models.children[0].children[0].children.push(objConfig);
break;
default:
}
});
resolve(models);
}
});
});
}

165
src/utils/earthMap/getLabelInfo.ts

@ -0,0 +1,165 @@
/**
*
* EarthComp.vue
*/
import { defHttp } from '/@/utils/http/axios';
import { addPin } from '@/utils/earthMap/earthObj';
import { useUserStore } from '/@/store/modules/user';
import { useEarthMapStore } from '/@/store/modules/earthMap';
import { earthMapUrl } from '@/api/earth/earthMap'
import hidePng from '@/assets/earthMap/hide.png';
import { setLabelStatus } from '@/utils/earthMap/setLabelStatus';
import { nextTick } from 'vue';
import $ from 'jquery';
let userStore = useUserStore();
let store = useEarthMapStore();
export default async function getLabelInfo(models, type) {
console.log("加载雷达和微波");
return new Promise((resolve, reject) => {
//请求地图标志信息
defHttp.get({ url: earthMapUrl.queryLabelList }, { isTransformResponse: false }).then(async (res) => {
// console.log("请求地图标志信息",res);
if (res.success) {
const labelItems = await setLabel(res.result, models, type);
resolve(labelItems);
}
});
});
}
async function setLabel(res, models, type) {
const args = { pageNo: 1, pageSize: 999 };
await defHttp
.get(
{
url: earthMapUrl.queryDeviceInfoList,
params: args,
},
{ isTransformResponse: false }
)
.then((reponse) => {
if (reponse.success) {
// console.log("queryDeviceInfoList",reponse);
const hostDeviceList = reponse.result.records;
for (const hostDevice of hostDeviceList) {
store.hostDeviceMapById.set(hostDevice.id, hostDevice);
}
return store.hostDeviceMapById;
} else {
console.error('获取主机信息错误', reponse);
}
})
.catch(() => {
throw '获取主机信息错误';
});
//根据经纬度算出该点地形高度
let posArr: any = [],
updatedPositions: any = [];
res.forEach((data, index) => {
updatedPositions.push(window.Cesium.Cartographic.fromDegrees(data.mapLabel.labelLon, data.mapLabel.labelLat, data.mapLabel.labelHeight));
});
const labelItems: any = [];
//设置标志
res.forEach((data, index) => {
const item: any = data.mapLabel;
labelItems.push(item.id);
const objConfig3 = {
ref: item.id,
name: item.lineId,
czmObject: {
customProp: '{"labelAttr":' + item.labelAttr + ',"labelCode":"' + item.labelCode + '","deviceId":"' + data.deviceId + '"}',
name: item.labelName,
xbsjType: 'Pin',
imageUrl: window._CONFIG['staticDomainURL'] + '/' + item.labelImgUrl,
position: [updatedPositions[index].longitude, updatedPositions[index].latitude, Number(item.labelHeight)],
scale: item.labelAttr == 4 ? 1 : 0.7,
pinBuilder: {
extText: item.labelName,
extTextFont: '30px 楷体',
extTextPixelOffset: item.labelAttr == 4 ? [30, -20] : [15, -20],
fillColor: [1, 1, 1, 0.9],
outlineColor: [0, 0, 0, 0.9],
},
far: 25000,
},
};
if (item.labelAttr == 4) {
// console.log("雷达",item);
store.statusByNodeId.set(item.id, 1);
addLabelNodeToTree(item, models, objConfig3, type);
} else {
// console.log("微波",item);
store.statusByNodeId.set(item.id, -10);
addLabelNodeToTree(item, models, objConfig3, type);
const device = store.hostDeviceMapById.get(data.deviceId);
if (device) {
//参数3 2为查询状态
setLabelStatus(device, item.labelCode, item.id, 2);
}
}
});
return labelItems;
}
function addLabelNodeToTree(item, models, objConfig3, type) {
//微波
if (item.labelAttr == 10) {
if (type == 2) {
let childs1 = models.children;
for (const child of childs1) {
if ('node_' + item.lineId == child.ref) {
child.children[2].children.push(objConfig3);
}
}
} else {
const parentNode = store.nodeConfigByRef.get('node_' + item.lineId);
if (!parentNode) {
return;
}
let childs2 = parentNode.children;
childs2[2].children.push(objConfig3);
}
}
//雷达
else if (item.labelAttr == 4) {
if (type == 2) {
let childs1 = models.children;
for (const child of childs1) {
if ('node_' + item.lineId == child.ref) {
child.children[1].children.push(objConfig3);
}
}
} else {
const parentNode = store.nodeConfigByRef.get('node_' + item.lineId);
if (!parentNode) {
return;
}
let childs2 = parentNode.children;
childs2[1].children.push(objConfig3);
}
}
//雷达(已弃用)
else if (item.labelAttr == 4) {
console.log('leida');
if (type == 2) {
let childs3 = models.children;
for (const child of childs3) {
for (const element of child.children[1].children) {
if ('nodeSecondary_' + item.lineId == element.ref) {
element.children.push(objConfig3);
}
}
}
} else {
const parentNode1 = store.nodeConfigByRef.get('nodeSecondary_' + item.lineId);
// console.log("nodeSecondary_",parentNode1);
if (!parentNode1) {
return;
}
const childs4 = parentNode1.children;
childs4.push(objConfig3);
}
}
}

2
src/utils/earthMap/getLineInfo.ts

@ -14,7 +14,7 @@ import $ from 'jquery';
let userStore = useUserStore();
let store = useEarthMapStore();
export default function getLineInfo(models, type) {
console.log("请求线路信息");
console.log("加载区域");
return new Promise((resolve, reject) => {
//请求线路信息

48
src/utils/earthMap/getPatrolRouteInfo.ts

@ -0,0 +1,48 @@
/**
* 线
* EarthComp.vue
*/
import { defHttp } from '/@/utils/http/axios';
import { useUserStore } from '/@/store/modules/user';
import { useEarthMapStore } from '/@/store/modules/earthMap';
import { earthMapUrl } from '@/api/earth/earthMap'
import earthUtils from '@/utils/earthMap/earth';
let userStore = useUserStore();
let store = useEarthMapStore();
export default function getPatrolRouteInfo(models) {
return new Promise((resolve, reject) => {
//执勤巡逻路线
defHttp.get({ url: earthMapUrl.queryPatrolRouteInfo }, { isTransformResponse: false }).then(async (res) => {
if (res.success) {
res.result.forEach((data, index) => {
//将路线上的点拼成坐标数组
let positions: any = [];
data.msLineConstList.forEach((data, index) => {
positions.push(earthUtils.degreeToRadianInLngLatHeight(data.lon, data.lat, data.height));
});
const objConfig = {
ref: data.lineCode,
czmObject: {
name: data.lineName,
xbsjType: 'Polyline',
width: 2,
material: {
type: 'XbsjODLineMaterial',
XbsjODLineMaterial: {
bgColor: [0.5, 0.5, 0.5, 1],
color: [0, 1, 0.11, 1],
totoalFrameCount: 200,
},
},
positions: positions,
},
};
models.children[0].children.push(objConfig);
});
resolve(models);
}
});
});
}

2
src/utils/earthMap/guid.ts

@ -1,5 +1,5 @@
// 随机数
export function guid() {
export default function guid() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = (Math.random() * 16) | 0,
v = c == 'x' ? r : (r & 0x3) | 0x8;

10
src/utils/earthMap/handleNodeType.ts

@ -1,3 +1,6 @@
/**
* EarthComp.vue
*/
export default class HandleNodeType {
#sn;
#sensorCallback;
@ -59,4 +62,9 @@ export default class HandleNodeType {
this.#default ? this.#default() : null;
}
}
}
}
//调用方法
export function handleNodeType(sn) {
return new HandleNodeType(sn);
};

4
src/utils/earthMap/keyControlInit.ts

@ -1,5 +1,6 @@
/**
*
* EarthComp.vue
*/
import { h, computed, defineComponent, ref, onMounted, onBeforeMount, getCurrentInstance, onBeforeUnmount, nextTick, watch } from 'vue'
import { defHttp } from '/@/utils/http/axios';
@ -31,7 +32,8 @@ interface FireFenceItem {
export async function keyControlInit() {
export default async function keyControlInit() {
console.log("重点监控区域初始化");
// const { proxy }: any = getCurrentInstance();
defHttp.get({
url: '/military/dtKeyControlArea/list',

437
src/utils/earthMap/listenMouseHandler.ts

@ -0,0 +1,437 @@
/**
*
* EarthComp.vue
*
*/
import { nextTick } from 'vue';
import { defHttp } from '/@/utils/http/axios';
import $ from 'jquery';
import { useUserStore } from '/@/store/modules/user';
import { useEarthMapStore } from '/@/store/modules/earthMap';
import { earthMapUrl } from '@/api/earth/earthMap'
import { useMessage } from '/@/hooks/web/useMessage';
import { CircleScan } from '@/utils/earthMap/radarEntity';
import { radianToDegreeInLngLatHeight } from '@/utils/earthMap/earth';
import $mitt from '@/utils/earthMap/mitt';
let userStore = useUserStore();
let store = useEarthMapStore();
const { createMessage } = useMessage();
export default function listenMouseHandler(that) {
const handler = new window.Cesium.ScreenSpaceEventHandler(window.$viewer.scene.canvas);
that._handler = handler;
//取消双击旋转事件
window.$viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(window.Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
/* MOUSE事件(有性能问题,慎用!) */
/* 鼠标左键事件 */
{
handler.setInputAction((click: any) => {
if (typeof that._pin !== 'undefined') {
// 销毁指示线
that._pin.destroy();
}
let pickedFeature = window.$viewer.scene.pick(click.position);
console.log('点击:', pickedFeature);
if (pickedFeature && pickedFeature.id) {
// 三维模型
if (pickedFeature.id.xbsjType && pickedFeature.id.xbsjType === 'Model') {
//点击电线杆触发弹窗
store.cameraData.forEach((data) => {
if (!$.isEmptyObject(data.msCameraSiteList)) {
if (!data.msCameraSiteList) {
return;
}
data.msCameraSiteList.forEach((data) => {
if (pickedFeature.id.customProp === data.id) {
if ($('.cameraModal ul').length > 0) {
$('.cameraModal ul').remove();
}
$('.cameraModal').append('<ul></ul>');
if (!data.msCameraSettingList) return;
// 将监控相机列表传入弹窗组件中
that.cameraList = data.msCameraSettingList;
// 将监控点位置传入弹窗组件中
that.monitorPosition = pickedFeature.id._primitive.xbsjPosition;
data.msCameraSettingList.forEach((data, index) => {
let camera_img =
data.type == '4'
? window._CONFIG['staticDomainURL'] + '/qiuji.png'
: data.type == '3'
? window._CONFIG['staticDomainURL'] + '/qiangji.png'
: window._CONFIG['staticDomainURL'] + '/qiangji.png';
let cameraStatus = data.status == '1' ? 'successStatus' : data.status == '2' ? 'offlineStatus' : 'errorStatus';
let rtspUrl = data.cameraCode;
// 'rtsp://' + data.user + ':' + data.password + '@' + data.ip + window._CONFIG['cameraMain']
$('.cameraModal ul').append(
'<li><a class="openIframe" id="' +
data.id +
'" videoUrl="' +
rtspUrl +
'" cameraIP="' +
data.ip +
'" cameraUser="' +
data.user +
'" cameraPsd="' +
data.password +
'"><img src="' +
camera_img +
'" /><div class="' +
cameraStatus +
'">' +
data.cameraName +
'</div> </a></li>'
);
});
let cameraModal: any = document.getElementById('cameraModal')
cameraModal.style.left = click.position.x + -45 + 'px';
cameraModal.style.top = click.position.y + -180 + 'px';
that.cameraModalShow = true;
}
});
}
});
}
// 船只模型
if (pickedFeature.id.xbsjType && pickedFeature.id.name.includes('船') && pickedFeature.id.xbsjType === 'Model') {
that.AISInfoWindowShow = true;
// 赋值船只场景id
that.ship_guid = pickedFeature.id.guid;
}
//雷达扫描范围
if (
pickedFeature.id._xbsjOwner &&
pickedFeature.id._xbsjOwner.customProp &&
JSON.parse(pickedFeature.id._xbsjOwner.customProp).labelAttr == '4'
) {
let labelCode = JSON.parse(pickedFeature.id._xbsjOwner.customProp).labelCode;
console.log(pickedFeature.id._xbsjOwner);
if (pickedFeature.id._xbsjOwner.addViewShedReturn) {
//显示/不显示雷达扫码效果
// pickedFeature.id._xbsjOwner.addViewShedReturn.show = !pickedFeature.id._xbsjOwner.addViewShedReturn.show;
// console.log("pickedFeature.id._xbsjOwner.addViewShedReturn",pickedFeature.id._xbsjOwner.addViewShedReturn);
//清空当前雷达,并将该方法指向undefined(清空)
pickedFeature.id._xbsjOwner.addViewShedReturn.clear();
pickedFeature.id._xbsjOwner.addViewShedReturn = undefined;
} else {
defHttp.get({ url: earthMapUrl.radarList, params: { radarCode: labelCode } }, { isTransformResponse: false }).then((res) => {
if (res.success) {
if (res.result.records.length > 0) {
let data = res.result.records[0];
let rgb;
if (data.customProp) {
rgb = JSON.parse(data.customProp).color;
}
let radarRadius = data.workingRadius;
let radarRange = data.elevation;
let radarShifting = data.angularRadian;
let left = Number(radarShifting) - Number(radarRange) / 2;
//参数:经纬度、半径、起始角度(正北方向)、结束角度
console.log('雷达扫描范围', data);
//弧度转角度
let degreePosition = radianToDegreeInLngLatHeight(
pickedFeature.id._xbsjOwner.position[0],
pickedFeature.id._xbsjOwner.position[1],
0.1
);
//创建雷达扫描 深度
// window.$viewer.scene.globe.depthTestAgainstTerrain = true;
let rader = new CircleScan(window.$viewer);
rader.add(degreePosition, null, radarRadius, 10000);
pickedFeature.id._xbsjOwner.addViewShedReturn = rader;
// 雷达扫描2
// let rader2 = window.$viewer.entities.add({
// position: Cesium.Cartesian3.fromDegrees(113.528333, 22.156109),
// name: '雷达扫描',
// ellipse: {
// semiMajorAxis: 5000.0,
// semiMinorAxis: 5000.0,
// material: new Cesium.RadarScanMaterialProperty({
// color: new Cesium.Color(1.0, 1.0, 0.0, 0.7),
// speed: 20.0,
// }),
// height: 20.0,
// heightReference: Cesium.HeightReference.RELATIVE_TO_GROUND,
// outline: true,
// outlineColor: new Cesium.Color(1.0, 1.0, 0.0, 1.0)
// }
// })
// pickedFeature.id._xbsjOwner.addViewShedReturn= addViewShedRadar(
// pickedFeature.id._xbsjOwner.position,
// radarRadius,
// left,
// Number(radarRange) / 2 + Number(radarShifting),
// [rgb.r / 255, rgb.g / 255, rgb.b / 255, rgb.a]
// );
}
}
});
}
}
} else {
//关闭所有气泡窗
that.cameraModalShow = false;
that.poiModalShow = false;
}
}, window.Cesium.ScreenSpaceEventType.LEFT_CLICK);
}
/* 鼠标右键事件 */
{
handler.setInputAction((click) => {
// 判断点击位置是否有实体
//返回具有 `primitive` 属性的对象,该属性包含场景中特定窗口坐标处的第一个(顶部)图元,如果该位置没有任何内容,则返回未定义的对象。其他属性可能会根据基元的类型进行设置,并可用于进一步识别拾取的对象。
let pickedFeature = window.$viewer.scene.pick(click.position);
// console.log("pick",pickedFeature);
let entity = pickedFeature && pickedFeature.id;
console.log('pick', pickedFeature);
console.log('entity', entity);
if (entity == undefined) {
return;
}
if (typeof pickedFeature !== 'undefined' && pickedFeature.id.xbsjType == 'Model') {
//点击电线杆触发弹窗
store.cameraData.forEach((data) => {
if (!$.isEmptyObject(data.msCameraSiteList)) {
if (!data.msCameraSettingList) {
return;
}
data.msCameraSiteList.forEach((data) => {
if (pickedFeature.id.customProp === data.id) {
window.$uia.contextMenu.pop([
{
text: '监控视域分析属性',
func: () => {
let testConfig = {
ref: 'testView',
name: '雷达视域分析',
position: [1.514482876761954, 0.8497520519403554, -0.7553906497788317],
rotation: [4.535844766941594, 0.32288591161895097, 0],
near: 1,
far: 400,
fovH: Math.PI / 3,
fovV: Math.PI / 6,
show: false,
};
let Viewshed = new window.XE.Obj.Viewshed(window.$earth);
Viewshed.xbsjFromJSON(testConfig);
window.$uia.showPropertyWindow(Viewshed);
},
},
]);
}
});
}
});
}
//巡检监控视频
else if (typeof pickedFeature !== 'undefined' && entity._name == '视频图元') {
// console.log(pickedFeature)
// console.log("entity",entity)
window.$uia.contextMenu.pop([
{
text: '编辑',
func: () => {
$mitt.emit('addRoamPathVideoClose');
// store.commit('customPrimitive', entity.xbsjGuid);
store.customPrimitive = entity.xbsjGuid;
// 打开对应的创建巡检视频窗口
nextTick(() => {
that.addRoamVideoShow = true;
});
},
},
{
text: '删除',
func: () => {
window.$uia.confirm('确认删除?', () => {
defHttp
.delete(
{
url: '/military/msAreaCustomPrimitive/delete',
params: { id: entity.id },
},
{ isTransformResponse: false, joinParamsToUrl: true }
)
.then((response) => {
if (response.code == 200) {
let customPrimitiveList = store.customPrimitiveList;
// console.log("a",customPrimitiveList);
customPrimitiveList.forEach((element, index) => {
const model = window.$earth.getObject(element);
// console.log("model.id",model.id);
// console.log("entity.id",entity.id);
if (model.id == entity.id) {
let customPrimitive = customPrimitiveList.splice(index, 1)[0];
model.destroy();
}
});
// store.dispatch('asyncCustomPrimitive', customPrimitiveList);
store.customPrimitiveList = customPrimitiveList;
// notification.close("RoamVideoSet");
// sessionStorage.setItem("RoamVideoSet", "false");
} else {
createMessage.error('修改失败', 2);
console.error('删除失败', response);
}
})
.catch((res) => {
console.error('错误', res);
});
});
},
},
]);
}
//绘画图形
else if (typeof pickedFeature !== 'undefined' && entity.name == '绘画') {
// console.log("entity", entity);
window.$uia.contextMenu.pop([
{
text: '编辑',
func: () => {
window.$uia.showPropertyWindow(entity);
//记录编辑前信息
let oldEntity = {
depthTest: entity.depthTest, //深度检测
color: [...entity.color], //颜色
outline: {
color: [...entity.outline.color], //边框颜色
show: entity.outline.show, //边框显示
width: entity.outline.width, //边框宽度
},
positions: [...entity.positions],
};
nextTick(() => {
// 主要ui窗口
const mainUI = window.$uia._vm.$refs.mainUI;
// 所有打开的ui窗口Ref值
const windowsAttrList = Object.keys(mainUI.$refs);
// 寻找当前窗体的工具对象
const modelToolKey = windowsAttrList.filter((f) => f.indexOf(entity.guid) > -1)[0];
const modelTool = mainUI.$refs[modelToolKey][0];
// 当前窗体的元素
const el = modelTool.$el;
// this.cloneEl(el)
// 样式
el.style.width = '380px'; //宽度
el.children[2].style.padding = '0px';
el.children[2].style.transition = 'none';
el.children[2].children[0].children[0].style.minWidth = '370px';
// 关闭名称input
el.children[2].children[0].children[0].children[0].style.display = 'none';
// 关闭创建按钮
el.children[2].children[0].children[0].children[1].children[0].children[1].style.display = 'none';
// 关闭贴地
el.children[2].children[0].children[0].children[2].children[0].style.display = 'none';
// 关闭拉伸
el.children[2].children[0].children[0].children[3].children[0].style.display = 'none';
el.children[2].children[0].children[0].children[3].children[1].style.display = 'none';
el.children[2].children[0].children[0].children[3].children[2].style.display = 'none';
el.children[2].children[0].children[0].children[3].children[3].style.marginLeft = '8px';
// 右上角关闭
const cancelTopRightBtn = el.children[1].children[1];
// 取消按钮元素
const cancelBtn = el.children[3].children[0];
// 确认按钮元素
const okBtn = el.children[3].children[1];
// 取消按钮
cancelTopRightBtn.onclick = cancelBtn.onclick = function () {
//恢复原来设置
// console.log("oldEntity", oldEntity);
// console.log("entity", entity);
// entity.xbsjFromJSON(oldEntity)
// entity = JSON.parse(oldEntity)
entity.depthTest = oldEntity.depthTest;
entity.color = oldEntity.color;
entity.outline = oldEntity.outline;
entity.positions = oldEntity.positions;
entity.editing = false;
};
okBtn.onclick = function () {
let params = {
id: entity.customProp?.id,
drawData: JSON.stringify(entity),
};
// console.log("submit", entity);
defHttp
.post(
{
url: '/military/dtMapDraw/edit',
params: params,
},
{ isTransformResponse: false }
)
.then(() => {
createMessage.success('编辑成功', 2);
})
.catch(() => {
createMessage.error('编辑失败', 2);
});
};
});
},
},
{
text: '删除',
func: () => {
window.$uia.confirm('确认删除?', () => {
defHttp
.delete(
{
url: '/military/dtMapDraw/delete',
params: { id: entity.customProp?.id },
},
{ isTransformResponse: false, joinParamsToUrl: true }
)
.then((response) => {
if (response.code == 200) {
let shapeList = store.shapeList;
shapeList.forEach((element, index) => {
const model = window.$earth.getObject(element);
if (model.id == entity.customProp?.id) {
let shape = shapeList.splice(index, 1)[0];
model.destroy();
}
});
store.shapeList = shapeList;
} else {
createMessage.error('删除失败', 2);
console.error('删除失败', response);
}
})
.catch((res) => {
console.error('错误', res);
});
});
},
},
]);
}
}, window.Cesium.ScreenSpaceEventType.RIGHT_CLICK); //右键事件
}
/* picked事件 */
{
/* let canvasbox = window.$viewer.canvas, pickPosition = {}, cameraModal = this.$refs.cameraModal;//cameraModal组件
canvasbox.onclick = e => {
pickPosition.x = e.offsetX;
pickPosition.y = e.offsetY;
var picked = window.$viewer.scene.pick(pickPosition);
console.log("picked", picked);
if (picked !== undefined && picked.id !== undefined) {
console.log(e)
} else {
that.cameraModalShow = false;
}
} */
}
}

8
src/utils/earthMap/listenMouseHandlerSence.ts

@ -1,5 +1,5 @@
/**
*
*
* EarthComp.vue
*
*/
@ -16,7 +16,7 @@ const cursorCss = ref("grab");
let position: any = null;
let rotation: any = null;
let fov: any = null;
export function listenMouseHandlerSence(enablePointer = false, that) {
export default function listenMouseHandlerSence(enablePointer = false, that) {
viewer = window.$earth.czm.viewer;
window.viewer = viewer;
window.$earth.interaction.picking.enabled = true;
@ -53,6 +53,8 @@ export function listenMouseHandlerSence(enablePointer = false, that) {
//destroy方法有问题无法成功销毁,故选择trycatch
try {
console.log("pin",pin);
pin && pin.destroy();
pin = undefined
} catch (error) {
@ -70,7 +72,7 @@ export function listenMouseHandlerSence(enablePointer = false, that) {
rotation = [window.$earth.camera.rotation[0], window.$earth.camera.rotation[1], window.$earth.camera.rotation[2]];
fov = window.$earth.camera.fov;
that.$emit("checkPosition", position, cposition, rotation, fov);
},
window.Cesium.ScreenSpaceEventType.LEFT_CLICK
);

2
src/utils/earthMap/radarEntity.ts

@ -1,7 +1,7 @@
/**
*
* (viewer)
*
* EarthComp.vue
*/
class CircleScan {

918
src/utils/earthMap/sceneTreePopContextMenu.ts

@ -0,0 +1,918 @@
/**
* -
* EarthComp.vue
*/
import { defHttp } from '/@/utils/http/axios';
import { cloneModel, cloneShamNode } from '@/utils/earthMap/clone';
import { useUserStore } from '/@/store/modules/user';
import { useEarthMapStore } from '/@/store/modules/earthMap';
import { setLabelStatus, setAllLabelStatus } from '@/utils/earthMap/setLabelStatus';
import { earthMapUrl } from '@/api/earth/earthMap'
import { useMessage } from '/@/hooks/web/useMessage';
import { handleNodeType } from '@/utils/earthMap/handleNodeType';
import setIconByRef from '@/utils/earthMap/setIconByRef';
import { nextTick } from 'vue';
import _ from 'lodash';
import $mitt from '@/utils/earthMap/mitt';
import $ from 'jquery';
let userStore = useUserStore();
let store = useEarthMapStore();
const { createMessage } = useMessage();
export default function sceneTreePopContextMenu({ item, vueObject }, earthUI, that) {
let earth = window.$earth;
let XE = window.XE;
let sceneTree = earthUI.tools.sceneTree;
let sceneTreeComp = sceneTree._comp;
// 转换方法
let transform = window.Cesium.Math;
//右键之后设置当前 node
item._inner.sn.isSelected = true;
const el = vueObject.$el;
let baseItems: any = [
{
text: '克隆',
keys: '',
func: () => {
let sn: any = null;
if (item._inner.sn.ref.startsWith('node_')) {
const objectId = item._inner.sn.ref.split('_')[1];
sn = earth.sceneTree.$refs[objectId];
} else {
sn = item._inner.sn;
}
if (sn) {
let newSn: any = null;
let newSnData: any = null;
let index = 0;
if (sn.czmObject.xbsjType !== 'Polyline') {
index = cloneModel(sn);
newSn = sn.parent.children[index - 1];
newSnData = newSn.czmObject;
if (newSnData.xbsjType === 'Model') {
nextTick(() => {
const divs = $('#earthContainer>div>div>div:nth-child(5)')
.children('div')
.eq(1)
.children()
.eq(0)
.children()
.eq(0)
.children()
.each((index, element) => {
if (index <= 1) {
return;
}
const paddingLeft = $(element).children().eq(0).css('padding-left');
if (paddingLeft === '10px') {
$(element).css('display', 'none');
}
});
});
}
}
// 保存数据到数据库中
handleNodeType(sn)
// 传感器
.sensor(() => {
// debugger
// 设置 ref 属性 防止数据库中 eventSerialNum 重复
newSn.ref += '_copy';
// 发送请求 保存到数据库中
let saveSensorModelParameter = {
eventSerialNum: newSn.ref,
lon: transform.toDegrees(newSnData.xbsjPosition[0]).toFixed(5),
lat: transform.toDegrees(newSnData.xbsjPosition[1]).toFixed(5),
height: newSnData.xbsjPosition[2].toFixed(2),
yaw: transform.toDegrees(newSnData.xbsjRotation[0]).toFixed(2),
pitch: transform.toDegrees(newSnData.xbsjRotation[1]).toFixed(2),
roll: transform.toDegrees(newSnData.xbsjRotation[2]).toFixed(2),
isShow: 1,
modelType: '11',
eventType: 1,
};
defHttp.post(
{
url: earthMapUrl.SaveSensorModel,
params: saveSensorModelParameter,
},
{ isTransformResponse: false }
).then((res) => {
if (res.success) {
createMessage.success('克隆成功');
} else {
newSn.parent.children.splice(index, 1);
createMessage.error('克隆成功:' + res.message);
}
});
})
// 标志点 微波雷达回调
.markerPosition(() => {
newSn.title += '_copy';
let pinImage = newSnData.imageUrl;
const staticDomainURL = window._CONFIG['staticDomainURL'] + '/';
// 去除 image 地址中的 staticDomainURL 链接
let imageUri = pinImage.substring(pinImage.indexOf(staticDomainURL) + staticDomainURL.length, pinImage.length);
const jsonObj = JSON.parse(newSnData.customProp);
const labelAttr = jsonObj.labelAttr;
let savePinModelParameter = {
mapLabel: {
labelName: newSnData.name,
labelLon: transform.toDegrees(newSnData.position[0]).toFixed(5),
labelLat: transform.toDegrees(newSnData.position[1]).toFixed(5),
labelHeight: newSnData.position[2].toFixed(2),
labelImgUrl: imageUri,
// 1 启用, 0 禁用
labelStatus: 1,
// 标记属性-> 3: 标记位置
labelAttr: labelAttr,
labelCode: '',
lineId: newSn.name,
},
deviceId: jsonObj.deviceId,
};
defHttp.post(
{
url: earthMapUrl.saveMapLabel,
params: savePinModelParameter,
}, { isTransformResponse: false }
).then((res) => {
if (res.success) {
// 修改 ref 成 数据库返回的 id
newSn.ref = res.result;
setIconByRef(newSn.ref, newSn.ref);
newSn.czmObject.pinBuilder.extText = newSnData.name;
jsonObj.labelCode = '';
newSn.czmObject.customProp = JSON.stringify(jsonObj);
// 保存成功
createMessage.success('克隆成功');
} else {
newSn.parent.children.splice(index, 1);
createMessage.error('克隆失败' + res.message);
}
})
.catch((err) => {
newSn.parent.children.splice(index, 1);
createMessage.error('克隆失败');
});
})
//区域回调
.polylineCallBack(() => {
// debugger
const currentModel = new window.XE.Obj.Polyline(window.$earth);
const submitData: any = {};
const poistions = sn.czmObject.positions;
if (poistions.length <= 0) {
return;
}
submitData.name = sn.czmObject.name + '_copy';
submitData.lineCode = currentModel.guid;
submitData.isLoop = Number(sn.czmObject.loop);
submitData.isDepthCheck = Number(sn.czmObject.depthTest);
submitData.width = sn.czmObject.width;
submitData.interpolation = sn.czmObject.arcType;
submitData.positions = JSON.stringify(poistions);
switch (sn.czmObject.material.type) {
// 实线
case 'XbsjColorMaterial':
submitData.materialType = 0;
submitData.color = JSON.stringify(sn.czmObject.material.XbsjColorMaterial.color);
submitData.intervalColor = null;
submitData.dashLength = 0;
submitData.dashStyle = 0;
break;
// 虚线
case 'XbsjPolylineDashMaterial':
submitData.materialType = 1;
submitData.color = JSON.stringify(sn.czmObject.material.XbsjPolylineDashMaterial.color);
submitData.intervalColor = JSON.stringify(sn.czmObject.material.XbsjPolylineDashMaterial.gapColor);
submitData.dashLength = sn.czmObject.material.XbsjPolylineDashMaterial.dashLength;
submitData.dashStyle = sn.czmObject.material.XbsjPolylineDashMaterial.dashPattern;
break;
// 箭头线
case 'XbsjPolylineArrowMaterial':
submitData.materialType = 2;
submitData.color = JSON.stringify(sn.czmObject.material.XbsjPolylineArrowMaterial.color);
submitData.intervalColor = null;
submitData.dashLength = 0;
submitData.dashStyle = 0;
break;
// 轨迹线
case 'XbsjODLineMaterial':
submitData.materialType = 3;
submitData.color = JSON.stringify(sn.czmObject.material.XbsjODLineMaterial.color);
submitData.intervalColor = null;
submitData.dashLength = 0;
submitData.dashStyle = 0;
submitData.cycleFrame = sn.czmObject.material.XbsjODLineMaterial.totoalFrameCount;
break;
}
defHttp
.post(
{
url: earthMapUrl.saveMapLine,
params: submitData,
},
{ isTransformResponse: false }
)
.then((response) => {
if (response.success) {
currentModel.name = submitData.name;
currentModel.loop = submitData.isLoop;
currentModel.depthTest = submitData.isDepthCheck;
currentModel.width = submitData.width;
currentModel.arcType = submitData.interpolation;
currentModel.positions = JSON.parse(submitData.positions);
switch (sn.czmObject.material.type) {
// 实线
case 'XbsjColorMaterial':
currentModel.material.type = 'XbsjColorMaterial';
currentModel.material.color = submitData.color;
break;
// 虚线
case 'XbsjPolylineDashMaterial':
currentModel.material.type = 'XbsjPolylineDashMaterial';
currentModel.material.color = submitData.color;
currentModel.material.XbsjPolylineDashMaterial.gapColor = submitData.intervalColor;
currentModel.material.XbsjPolylineDashMaterial.dashLength = submitData.dashLength;
currentModel.material.XbsjPolylineDashMaterial.dashPattern = submitData.dashStyle;
break;
// 箭头线
case 'XbsjPolylineArrowMaterial':
currentModel.material.type = 'XbsjPolylineArrowMaterial';
currentModel.material.XbsjPolylineArrowMaterial.color = submitData.color;
break;
// 轨迹线
case 'XbsjODLineMaterial':
currentModel.material.type = 'XbsjODLineMaterial';
currentModel.material.XbsjODLineMaterial.color = submitData.color;
currentModel.material.XbsjODLineMaterial.totoalFrameCount = submitData.cycleFrame;
break;
}
const leaf = new XE.SceneTree.Leaf(currentModel);
leaf.ref = response.result;
sn.parent.children.push(leaf);
} else {
throw '克隆区域数据出错';
}
})
.catch((e) => {
currentModel.destroy();
createMessage.error('克隆区域数据出错', 3);
});
})
//监控点
.modelCallback(() => {
createMessage.warning('监控点不支持克隆');
})
.run();
}
},
},
{
text: '删除',
keys: '',
func: () => {
earthUI.confirm('确认删除图层?', () => {
try {
// debugger
let sn: any = null;
const ref = item._inner.sn.ref;
// update:-- 判断方式要修改
if (ref.startsWith('node_')) {
const objectId = item._inner.sn.ref.split('_')[1];
sn = earth.sceneTree.$refs[objectId];
} else {
sn = item._inner.sn;
}
let id = sn.ref;
// 删除数据库中的数据
handleNodeType(sn)
// 传感器
.sensor(() => {
// 发送请求 删除数据库中的数据
handlerModelDelete(earthMapUrl.deleteSensor, { eventSerialNum: id });
})
// 标志点
.markerPosition(() => {
if (sn.czmObject.addViewShedReturn) {
window.$earth.czm.viewer.entities.remove(sn.czmObject.addViewShedReturn);
}
if (sn.czmObject.customProp) {
let prop = JSON.parse(sn.czmObject.customProp);
if (prop.labelAttr == 4) {
defHttp.delete(
{
url: '/military/RadarConfig/deleteByRadarCode',
params: { radarCode: prop.labelCode },
},
{ isTransformResponse: false, joinParamsToUrl: true }
);
}
}
handlerModelDelete(earthMapUrl.deleteMapLabel, {
id: id,
});
})
// 线
.modelCallback(() => {
handlerModelDelete(earthMapUrl.deleteSite, { id: id }).then(() => {
sn.destroy();
const node = item._inner.sn;
const childList = node.parent.children;
childList.splice(childList.indexOf(node), 1);
node.destroy();
});
})
.polylineCallBack(() => {
const childList = item._inner.sn.children;
for (const child of childList) {
if (child.children.length > 0) {
createMessage.warning('存在下级数据无法删除');
throw '存在下级数据无法删除';
}
}
handlerModelDelete(earthMapUrl.deleteMapLine, { id: id }).then(() => {
const nodeRef = 'node_' + id;
const node = window.$earth.sceneTree.$refs[nodeRef];
const childList = node.parent.children;
childList.splice(childList.indexOf(node), 1);
node.destroy();
});
})
.run();
const index = sn.parent.children.indexOf(sn);
sn.parent.children.splice(index, 1);
} catch (error) { }
});
},
},
];
const bf = {
text: '布防/撤防',
keys: '',
func: () => {
const xbsjObject = item._inner.sn;
if (!xbsjObject || !xbsjObject.czmObject) return;
const jsonObj = JSON.parse(xbsjObject.czmObject.customProp);
const deviceId = jsonObj.deviceId;
if (!deviceId) {
console.error('主机设备为空');
return;
}
const labelCode = jsonObj.labelCode;
if (!labelCode) {
console.error('设备编码为null');
return;
}
const device = store.hostDeviceMapById.get(deviceId);
const ref = xbsjObject.ref;
if (device.deviceType_dictText.indexOf('微波探测器') > -1) {
if (ref && ref.length > 0) {
const state = store.statusByNodeId.get(ref);
if (state == 1) {
setLabelStatus(device, labelCode, ref, 0).then((response) => {
setIconByRef(ref, el);
});
} else if (state == 0) {
setLabelStatus(device, labelCode, ref, 1).then((response) => {
setIconByRef(ref, el);
});
} else {
createMessage.error('设备不在线');
}
}
} else if (device.deviceType_dictText.indexOf('雷达') > -1) {
// console.log("leida");
//处理单个雷达布防撤防
//参数
// {
// "regionIdList": [
// 2
// ], // 周界防区区域ID列表(雷达设备列表的ID)
// "regionStatus": 0, // 布防状态 0 - 未布防 1 - 布防
// "defenceRule": { // 布防规则
// "startTime": "yyyy-MM-dd HH:mm:ss", // 布防开始时间 每日循环情况下只包含时分秒,格式:"HH:mm:ss" 非每日循环情况下包含年月日、时分秒,格式:"yyyy-MM-dd HH:mm:ss"
// "endTime": "yyyy-MM-dd HH:mm:ss", // 布防结束时间 每日循环情况下只包含时分秒,格式:"HH:mm:ss" 非每日循环情况下包含年月日、时分秒,格式:"yyyy-MM-dd HH:mm:ss"
// "dailyCycle": true // 每日循环布防 true - 是 false - 否
// }
// }
// putAction(this.url.perimeterControl,{})
}
},
};
const selectRef = item._inner.sn.ref;
if (selectRef.startsWith('wbList') || selectRef.startsWith('nodeSecondary_')) {
baseItems = [
{
text: '一键布防',
keys: '',
func: () => {
setAllLabelStatus(selectRef, item, true);
},
},
{
text: '一键撤防',
keys: '',
func: () => {
setAllLabelStatus(selectRef, item, false);
},
},
];
earthUI.contextMenu.pop(baseItems);
return;
} else if (selectRef.startsWith('monitor') || selectRef.startsWith('ldList')) {
earthUI.contextMenu.pop([]);
return;
} else if (item.level <= 2) {
if (!item._inner.sn.ref.startsWith('node_')) {
earthUI.contextMenu.pop([]);
return;
} else {
baseItems.splice(0, 1);
}
} else {
if (selectRef.startsWith('camera')) {
// baseItems = [bf]
// earthUI.contextMenu.pop(baseItems)
return;
} else if (!selectRef.startsWith('node_')) {
//站点
baseItems.unshift({
type: 'divider',
});
baseItems.unshift(bf);
}
}
let num = 2;
//判断定位的位置
if (
item.level <= 2 ||
selectRef.startsWith('monitor') ||
selectRef.startsWith('wbList') ||
selectRef.startsWith('ldList') ||
//站点
selectRef.startsWith('node_')
)
num = 0;
baseItems.splice(num, 0, {
text: '定位',
keys: '',
func: () => {
// const czmObject = item._inner.sn.czmObject
// czmObject.flyTo()
const ref = item._inner.sn.ref;
let czmObject: any = null;
if (ref.startsWith('node_')) {
const objectId = ref.split('_')[1];
const sn = earth.sceneTree.$refs[objectId];
czmObject = sn.czmObject;
} else {
const sn = item._inner.sn;
czmObject = sn.czmObject;
}
czmObject.flyTo();
},
});
baseItems.push(
...[
{
type: 'divider',
},
{
text: '属性',
func: () => {
$mitt.emit('windowCancel');
// 属性面板
const mainUI = earthUI._vm.$refs.mainUI;
const areaCode = getAreaCode(item);
let sn: any = null;
if (item._inner.sn.ref.startsWith('node_')) {
const objectId = item._inner.sn.ref.split('_')[1];
sn = earth.sceneTree.$refs[objectId];
// window.XE.MVVM.watch(() => {
// item._inner.sn.title = sn.title
// })
sn.czmObject.distanceDisplayCondition = [1.0, 30000.0];
if (sn.czmObject.xbsjType == 'Model') {
const lineId = item.parent.parent._inner.sn.ref.split('_')[1];
that.czmObject = sn.czmObject;
that.node = item;
that.type = 'jkd';
that.lineId = lineId;
that.areaCode = areaCode;
that.areaByNodeIdModel = store.areaByNodeId;
nextTick(() => {
that.addModelWinShow = true;
});
return;
}
} else {
sn = item._inner.sn;
if (sn.czmObject.xbsjType == 'Pin') {
const jsonObj = JSON.parse(sn.czmObject.customProp);
const lineId = jsonObj.labelAttr == 4 ? item.parent._inner.sn.ref.split('_')[1] : item.parent.parent._inner.sn.ref.split('_')[1];
that.czmObject = sn.czmObject;
that.node = item;
that.type = jsonObj.labelAttr == 4 ? 'ld' : 'wb';
that.lineId = lineId;
that.areaCode = areaCode;
that.eidtId = sn.ref;
that.areaByNodeIdModel = store.areaByNodeId;
(that.el = el),
nextTick(() => {
that.addModelWinShow = true;
});
return;
}
}
let index = sn.parent.children.indexOf(sn);
let tempData = sn.czmObject.toAllJSON();
// 设置属性面板的确定按钮方法
// 显示属性面板
earthUI.showPropertyWindow(sn.czmObject);
nextTick(() => {
// 模型窗口
const windowsAttrList = Object.keys(mainUI.$refs);
// 找到该模型设置属性窗口
const modelToolKey = windowsAttrList.filter((f) => f.indexOf(sn.czmObject.guid || sn.guid) > -1)[0];
const modelTool = mainUI.$refs[modelToolKey][0];
// 对应处理方法
handleNodeType(sn)
// 感应器
.sensor(() => {
// 禁用模型名称编辑
modelTool.$el.getElementsByClassName('xbsj-flatten')[0].children[0].children[1].setAttribute('disabled', 'disabled');
})
.default(() => {
// 启用模型名称编辑
modelTool.$el.getElementsByClassName('xbsj-flatten')[0].children[0].children[1].removeAttribute('disabled');
})
.run();
// modelTool
modelTool.ok = () => {
// 确定时清除这个事件
$mitt.off('windowCancel');
// 保存前端数据
const modelToolObj = modelTool._czmObj;
if (!modelToolObj) {
return;
}
modelToolObj.positionEditing = false;
if (modelToolObj.isCreating) {
modelToolObj.isCreating = false;
const sceneObject = new XE.SceneTree.Leaf(modelToolObj);
earthUI.addSceneObject(sceneObject);
}
// 保存到数据库
propertiesWindowConfirm(modelTool, sn, index);
// 关闭属性面板
modelTool.close();
};
modelTool.cancel = () => {
// 清除这个事件
$mitt.off('windowCancel');
// 关闭属性面板
modelTool.close();
let t = modelTool._czmObj;
// 如果是创建的话,需要删除
t && t.positionEditing === false && t.isCreating && t.isCreating === false && t.destroy();
// 恢复之前的数据
t && t.xbsjFromJSON(tempData);
};
$mitt.on('windowCancel', modelTool.cancel);
// 下面的代码,是切换属性面板里选项窗口, 必须
// 否侧 ok cancel 等方法执行是原本的方法而不是已经修改的方法
modelTool.tabShow = '3';
modelTool.tabShow = '1';
});
},
},
]
);
// 右键菜单-重命名
// 先销毁之前的 on-change-title 事件
vueObject.$off('on-change-title', handleChangeTitle);
// 重命名时 on-change-title 事件
vueObject.$on('on-change-title', handleChangeTitle);
// 弹出右键菜单
earthUI.contextMenu.pop(baseItems);
}
// 右键菜单删除按钮的删除方法
export function handlerModelDelete(url, params) {
return defHttp
.delete(
{
url: url,
params: params,
},
{ isTransformResponse: false, joinParamsToUrl: true }
)
.then((res) => {
if (res.success) {
createMessage.success('删除成功');
} else {
createMessage.error('删除失败');
console.log('asdasdasd');
}
});
}
export function getAreaCode(item) {
const currentRef = item._inner.sn.ref;
if (!store.areaByNodeId.has(currentRef)) {
if (item.parent) {
return getAreaCode(item.parent);
}
} else {
return store.areaByNodeId.get(currentRef);
}
}
// 重命名 on-change-title 事件 使用 lodash.debounce 函数(防抖)
export const handleChangeTitle = _.debounce(function (options) {
const sn = options.item._inner.sn;
const newTitle = options.title;
// 修改模型属性后,提交到后台。先判断模型的节点,调用不同的接口
handleNodeType(sn)
// 感应器
.sensor(() => {
// 不支持修改名称
createMessage.warning('不支持修改感应器的名称');
})
// 传感器标志线
.modelCallback(() => {
// 发送请求 保存模型属性
let editCameraSiteModelParameter = {
id: sn.ref,
sitename: newTitle,
};
defHttp.put(
{
url: earthMapUrl.updateSite,
params: editCameraSiteModelParameter,
},
{ isTransformResponse: false }
).then((res) => {
if (res.success) {
createMessage.success('修改成功');
} else {
createMessage.error('修改失败');
}
})
.catch((error) => {
createMessage.error('修改失败');
});
})
.markerPosition(() => {
// 发送请求 保存模型属性
let editPinModelParameter = {
id: sn.ref,
labelName: newTitle,
};
defHttp
.put(
{
url: earthMapUrl.updateMapLabel,
params: editPinModelParameter,
},
{ isTransformResponse: false }
)
.then((res) => {
if (res.success) {
// 修改扩展文本
sn.czmObject.pinBuilder.extText = newTitle;
createMessage.success('修改成功');
} else {
createMessage.error('修改失败');
}
})
.catch((error) => {
createMessage.error('修改失败');
});
})
.run();
}, 150);
// 属性面板确定按钮方法
export function propertiesWindowConfirm(propertiesWindow, sn, index) {
// 属性面板 所修改的模型
let model: any = null;
if (sn.ref && !sn.ref.startsWith('node_')) {
model = sn;
} else {
model = sn.parent.children[index];
}
let modelData = model.czmObject;
// 转换方法
let transform = window.Cesium.Math;
// 修改模型属性后,提交到后台。先判断模型的节点,调用不同的接口
handleNodeType(sn)
// 传感器
.sensor(() => {
// 发送请求 保存模型属性
let editSensorParams = {
eventSerialNum: model.ref,
lon: transform.toDegrees(modelData.xbsjPosition[0]).toFixed(5),
lat: transform.toDegrees(modelData.xbsjPosition[1]).toFixed(5),
height: modelData.xbsjPosition[2].toFixed(2),
yaw: transform.toDegrees(modelData.xbsjRotation[0]).toFixed(2),
pitch: transform.toDegrees(modelData.xbsjRotation[1]).toFixed(2),
roll: transform.toDegrees(modelData.xbsjRotation[2]).toFixed(2),
isShow: 1,
// 传感器类型
modelType: '11',
// 事件类型
eventType: 1,
};
defHttp
.put(
{
url: earthMapUrl.updateSensor,
params: editSensorParams,
},
{ isTransformResponse: false }
)
.then((res) => {
if (res.success) {
createMessage.success('修改成功');
} else {
createMessage.error('修改失败: ' + res.message);
}
});
})
// 站点
.modelCallback(() => {
let startNum = modelData.url.lastIndexOf('/') + 1;
let modelName = '';
if (startNum > 0) {
modelName = modelData.url.substring(startNum, modelData.url.length);
}
// 发送请求 保存模型属性
let editCameraSiteModelParameter = {
id: model.ref,
longitude: transform.toDegrees(modelData.xbsjPosition[0]).toFixed(6),
latitude: transform.toDegrees(modelData.xbsjPosition[1]).toFixed(6),
height: modelData.xbsjPosition[2],
yaw: transform.toDegrees(modelData.xbsjRotation[0]).toFixed(6),
pitch: transform.toDegrees(modelData.xbsjRotation[1]).toFixed(6),
roll: transform.toDegrees(modelData.xbsjRotation[2]).toFixed(6),
modelUrl: modelName,
sitename: modelData.name,
};
defHttp
.put(
{
url: earthMapUrl.updateSite,
params: editCameraSiteModelParameter,
},
{ isTransformResponse: false }
)
.then((res) => {
if (res.success) {
modelData.pinBuilder.extText = modelData.name;
createMessage.success('修改成功');
} else {
createMessage.error('修改失败');
}
});
})
// 标志点
.markerPosition(() => {
let pinImage = modelData.imageUrl;
const staticDomainURL = window._CONFIG['staticDomainURL'] + '/';
// 去除 image 地址中的 staticDomainURL 链接
let imageUri = pinImage.substring(pinImage.indexOf(staticDomainURL) + staticDomainURL.length, pinImage.length);
let editPinModelParameter = {
id: model.ref,
labelName: modelData.name,
labelLon: transform.toDegrees(modelData.position[0]).toFixed(5),
labelLat: transform.toDegrees(modelData.position[1]).toFixed(5),
labelHeight: modelData.position[2].toFixed(2),
labelImgUrl: imageUri,
};
defHttp
.put(
{
url: earthMapUrl.updateMapLabel,
params: editPinModelParameter,
},
{ isTransformResponse: false }
)
.then((res) => {
if (res.success) {
modelData.pinBuilder.extText = modelData.name;
createMessage.success('修改成功');
} else {
createMessage.error('修改失败');
}
})
.catch((error) => {
createMessage.error('修改失败');
});
})
.polylineCallBack(() => {
const submitData: any = {};
const poistions = modelData.positions;
if (poistions.length <= 0) {
return;
}
submitData.id = model.ref;
submitData.name = modelData.name;
if (!modelData.customProp) {
submitData.lineCode = modelData.guid;
}
submitData.isLoop = Number(modelData.loop);
submitData.isDepthCheck = Number(modelData.depthTest);
submitData.width = modelData.width;
submitData.interpolation = modelData.arcType;
submitData.positions = JSON.stringify(poistions);
switch (modelData.material.type) {
// 实线
case 'XbsjColorMaterial':
submitData.materialType = 0;
// material.XbsjColorMaterial = {}
submitData.color = JSON.stringify(modelData.material.XbsjColorMaterial.color);
submitData.intervalColor = null;
submitData.dashLength = 0;
submitData.dashStyle = 0;
break;
// 虚线
case 'XbsjPolylineDashMaterial':
submitData.materialType = 1;
submitData.color = JSON.stringify(modelData.material.XbsjPolylineDashMaterial.color);
submitData.intervalColor = JSON.stringify(modelData.material.XbsjPolylineDashMaterial.gapColor);
submitData.dashLength = modelData.material.XbsjPolylineDashMaterial.dashLength;
submitData.dashStyle = modelData.material.XbsjPolylineDashMaterial.dashPattern;
// material.XbsjPolylineDashMaterial = {}
// material.XbsjPolylineDashMaterial.dashLength = data.dashLength
// material.XbsjPolylineDashMaterial.dashPattern = data.dashStyle
break;
// 箭头线
case 'XbsjPolylineArrowMaterial':
submitData.materialType = 2;
// material.XbsjPolylineArrowMaterial = {}
submitData.color = JSON.stringify(modelData.material.XbsjPolylineArrowMaterial.color);
submitData.intervalColor = null;
submitData.dashLength = 0;
submitData.dashStyle = 0;
break;
// 轨迹线
case 'XbsjODLineMaterial':
submitData.materialType = 3;
submitData.color = JSON.stringify(modelData.material.XbsjODLineMaterial.color);
submitData.intervalColor = null;
submitData.dashLength = 0;
submitData.dashStyle = 0;
submitData.cycleFrame = modelData.material.XbsjODLineMaterial.totoalFrameCount;
// material.XbsjODLineMaterial = {}
// material.XbsjODLineMaterial.color = JSON.parse(data.color)
// material.XbsjODLineMaterial.totoalFrameCount = data.cycleFrame
break;
}
defHttp
.put(
{
url: earthMapUrl.updateMapLine,
params: submitData,
},
{ isTransformResponse: false }
)
.then((res) => {
if (res.success) {
createMessage.success('修改成功!', 2);
sn.title = submitData.name;
window.$earth.sceneTree.$refs['node_' + sn.ref].title = submitData.name;
} else {
createMessage.error('修改失败', 2);
}
})
.catch((error) => {
createMessage.error('修改失败', 2);
});
})
.run();
}

36
src/utils/earthMap/setIconByRef.ts

@ -0,0 +1,36 @@
/**
*
* EarthComp.vue
*/
import { defHttp } from '/@/utils/http/axios';
import { useUserStore } from '/@/store/modules/user';
import { useEarthMapStore } from '/@/store/modules/earthMap';
import circleDot2 from '@/assets/earthMap/circleDot2.png';
import circleDot1 from '@/assets/earthMap/circleDot1.png';
import circleDot3 from '@/assets/earthMap/circleDot3.png';
let userStore = useUserStore();
let store = useEarthMapStore();
export default function setIconByRef(ref, el) {
const status = store.statusByNodeId.get(ref);
if (status != undefined && status != null) {
let img = store.imgByRef.get(ref);
const icon = el.children[0].children[2];
if (!img) {
img = document.createElement('img');
store.imgByRef.set(ref, img);
}
if (icon.nodeName == 'I') {
icon.replaceWith(img);
}
if (status == 1) {
img.src = circleDot2;
} else if (status == 0) {
img.src = circleDot1;
} else {
img.src = circleDot3;
}
img.setAttribute('style', 'width:16px;height:16px;margin-top:7px');
}
}

225
src/utils/earthMap/setLabelStatus.ts

@ -0,0 +1,225 @@
/**
* EarthComp.vue
*/
import { defHttp } from '/@/utils/http/axios';
import { useUserStore } from '/@/store/modules/user';
import { useEarthMapStore } from '/@/store/modules/earthMap';
import { earthMapUrl } from '@/api/earth/earthMap'
let userStore = useUserStore();
let store = useEarthMapStore();
export function setLabelStatus(device, labelCode, id, code) {
const args = {
device: device,
code: code, // 命令码:0-撤防 1-布防 2-状态查询 3-其他预留
deviceType: 2, // 设备类型:1-探测主机 2-探测器 3-串口设备 4-预留
deviceSn: labelCode, // 设备条码
};
// console.log("device",device);
if (device.deviceType_dictText.indexOf('微波探测器') > -1) {
// console.log("微波探测器");
return defHttp.post({ url: '/military/netty/microwaveDetector/maintenance', params: args }, { isTransformResponse: false })
.then((response) => {
if (response.success) {
const status = response;
store.statusByNodeId.set(id, status);
} else {
store.statusByNodeId.set(id, -10);
}
return response;
})
.catch((error) => {
store.statusByNodeId.set(id, -10);
return error;
})
} else if (device.deviceType_dictText.indexOf('雷达') > -1) {
store.statusByNodeId.set(id, 1);
//雷达周界防区列表
return defHttp
.get({ url: earthMapUrl.perimeterRegionList, params: { regionType: 2 } }, { isTransformResponse: false })
.then(
(res) => {
// console.log(res);
if (res.success) {
// (未测试)
res.result.forEach((element) => {
if (element.id == id) {
// this.statusByNodeId.set(id, element.isOnline)
}
});
} else {
store.statusByNodeId.set(id, 1);
}
return res;
},
(err) => {
store.statusByNodeId.set(id, 1);
return err;
}
)
.catch((err) => {
store.statusByNodeId.set(id, 1);
return err;
});
}
return Promise.resolve("未知错误");
}
export function setAllLabelStatus(selectRef, item, wbUnifiedResponse) {
//监控点
if (selectRef.startsWith('monitor')) {
let grandsons: any = [];
const childs = item.children;
for (const child of childs) {
const grandson1 = child.children;
if (grandson1 && grandson1.length > 0) {
grandsons = grandsons.concat(grandson1);
}
}
for (const grandson of grandsons) {
const xbsjObject = grandson._inner.sn;
const ref = xbsjObject.ref;
if (ref.startsWith('camera_')) {
const state = store.statusByNodeId.get(ref);
if (state == 1) {
store.statusByNodeId.set(ref, 0);
const img = store.imgByRef.get(ref);
img.src = require('@/assets/earthMap/circleDot1.png');
} else if (state == 0) {
store.statusByNodeId.set(ref, 1);
const img = store.imgByRef.get(ref);
img.src = require('@/assets/earthMap/circleDot1.png');
}
}
}
}
//微波
else if (selectRef.startsWith('wbList')) {
const parentNode = item.parent;
let areaCode = null;
if (parentNode) {
const falseNodeRef = item.parent._inner.sn.ref;
const nodeRef = falseNodeRef.split('_')[1];
const trueNode = window.$earth.sceneTree.$refs[nodeRef];
areaCode = trueNode.czmObject.customProp;
}
const childs1 = item.children;
if (!childs1 || childs1.length < 0) {
return;
}
const length = childs1.length;
let index = -1;
for (const child of childs1) {
index++;
let xbsjObject = child._inner.sn;
let jsonObj = JSON.parse(xbsjObject.czmObject.customProp);
let deviceId = jsonObj.deviceId;
let device = store.hostDeviceMapById.get(deviceId);
if (!device) {
console.error('主机设备为null');
continue;
}
const args = {
device: device,
isDefence: wbUnifiedResponse,
defenceArea: areaCode,
detectorList: null,
};
defHttp
.post(
{
url: earthMapUrl.setDefenseArea,
params: args,
},
{ isTransformResponse: false }
)
// postAction(this.url.setDefenseArea, args)
.then((response) => {
if (!response.success) {
return;
} else {
for (let i = index; i < length; i++) {
const child1 = childs1[i];
const xbsjObject1 = child1._inner.sn;
const ref1 = xbsjObject1.ref;
if (ref1 && ref1.length > 0) {
const state1 = store.statusByNodeId.get(ref1);
if (state1 == 0 && wbUnifiedResponse) {
store.statusByNodeId.set(ref1, 1);
const img1 = store.imgByRef.get(ref1);
if (!img1) return;
img1.src = require('@/assets/earthMap/circleDot2.png');
} else if (state1 == 1 && !wbUnifiedResponse) {
store.statusByNodeId.set(ref1, 0);
const img1 = store.imgByRef.get(ref1);
if (!img1) return;
img1.src = require('@/assets/earthMap/circleDot1.png');
}
}
}
}
console.log(response);
});
break;
}
} else if (selectRef.startsWith('nodeSecondary')) {
const childs1 = item.children;
if (!childs1 || childs1.length < 0) {
return;
}
for (const child of childs1) {
let xbsjObject = child._inner.sn;
let jsonObj = JSON.parse(xbsjObject.czmObject.customProp);
let deviceId = jsonObj.deviceId;
let device = store.hostDeviceMapById.get(deviceId);
if (!device) {
console.error('主机设备为null');
continue;
}
let regionIdList: any = [];
if (item.children.length > 0) {
item.children.forEach((element) => {
regionIdList.push(element._inner.sn.ref);
});
}
const args = {
regionIdList: regionIdList, // 周界防区区域ID列表(雷达设备列表的ID)
regionStatus: wbUnifiedResponse ? 1 : 0, // 布防状态 0 - 未布防 1 - 布防
defenceRule: {
// 布防规则
startTime: 'yyyy-MM-dd HH:mm:ss', // 布防开始时间 每日循环情况下只包含时分秒,格式:"HH:mm:ss" 非每日循环情况下包含年月日、时分秒,格式:"yyyy-MM-dd HH:mm:ss"
endTime: 'yyyy-MM-dd HH:mm:ss', // 布防结束时间 每日循环情况下只包含时分秒,格式:"HH:mm:ss" 非每日循环情况下包含年月日、时分秒,格式:"yyyy-MM-dd HH:mm:ss"
dailyCycle: true, // 每日循环布防 true - 是 false - 否
},
};
// putAction(this.url.perimeterControl,{})
console.log(device, store.statusByNodeId, xbsjObject);
let ref1 = xbsjObject.ref;
let state1 = store.statusByNodeId.get(ref1);
//一键布防撤防测试使用
if (wbUnifiedResponse) {
state1 = 0;
} else {
state1 = 1;
}
if (state1 == 0 && wbUnifiedResponse) {
store.statusByNodeId.set(ref1, 1);
const img1 = store.imgByRef.get(ref1);
if (!img1) return;
img1.src = require('@/assets/earthMap/circleDot2.png');
} else if (state1 == 1 && !wbUnifiedResponse) {
store.statusByNodeId.set(ref1, 0);
const img1 = store.imgByRef.get(ref1);
if (!img1) return;
console.log(img1);
img1.src = require('@/assets/earthMap/circleDot1.png');
}
// break
}
}
}

74
src/utils/earthMap/websocket.ts

@ -1,14 +1,22 @@
/**
* WebSocket
* EarthComp.vue
*/
import _ from 'lodash';
import $ from 'jquery';
import { useUserStore } from '/@/store/modules/user';
import { useEarthMapStore } from '/@/store/modules/earthMap';
import { defHttp } from '/@/utils/http/axios';
import $mitt from '@/utils/earthMap/mitt';
import { useMessage } from "/@/hooks/web/useMessage";
import earthUtils from '@/utils/earthMap/earth';
import alarmImg from '@/assets/earthMap/alarm.gif';
const { createMessage } = useMessage();
import { earthMapUrl } from '@/api/earth/earthMap'
const { createMessage } = useMessage();
let userStore = useUserStore();
let store = useEarthMapStore();
let websock: any = [];
function initWebSocket(configName) {
if ('WebSocket' in window) {
@ -73,7 +81,7 @@ const loreadAlarmInfo = _.debounce(
);
//
async function websocketonmessage(e) {
async function websocketonmessage(e, that) {
//接收后端数据
var data = eval('(' + e.data + ')');
const cesium = window.Cesium;
@ -96,7 +104,7 @@ async function websocketonmessage(e) {
//显示报警位置
window.$earth.sceneTree.$refs[data.labelCode].czmObject.color = [1, 0.09803921568627451, 0, 1];
} else if (data.msgTxt != undefined && data.dealStatus == 3) {
this.$notification.open({
that.$notification.open({
key: 'fenceInfo',
message: '围栏信息通知',
description: data.msgTxt + '!',
@ -114,13 +122,13 @@ async function websocketonmessage(e) {
//4.提示音
if (data.dealStatus !== 2 && data.dealStatus !== 0) {
await this.$refs.audio.play();
await that.$refs.audio.play();
setTimeout(() => {
this.$refs.audio.pause(); //N秒后暂停播放
that.$refs.audio.pause(); //N秒后暂停播放
}, data.alarmNum * 1000);
}
} else if (data.cmd == 'new_microwave_warn_info' || data.cmd == 'new_radar_warn_info' || data.cmd == 'new_video_warn_info') {
if (this.alarmInfoMap.has(data.serialNum)) {
if (store.alarmInfoMap.has(data.serialNum)) {
return;
}
const evalString = `
@ -197,7 +205,7 @@ async function websocketonmessage(e) {
pin.xbsjFromJSON(pinConfig);
scanline.xbsjFromJSON(scanlineConfig);
// 判断现在相机的高度来显示报警相关模型
if (this._earth.camera.position[2] < 100) {
if (window.$earth.camera.position[2] < 100) {
// 隐藏 pin, 显示 scanline
pin._div.hidden = true;
scanline.show = true;
@ -207,20 +215,20 @@ async function websocketonmessage(e) {
scanline.show = false;
}
scanline.flyTo();
this.alarmInfoMap.set(data.serialNum, { pin: pin, scanline: scanline, timestamp: Date.now() });
store.alarmInfoMap.set(data.serialNum, { pin: pin, scanline: scanline, timestamp: Date.now() });
//报警弹窗
this.videoWindowProps.title = `实时报警窗口(${data.cameraName}`;
this.videoWindowProps.videoUrl = data.cameraCode; //相机编码
this.videoWindowProps.isAlarm = true;
this.videoWindowProps.visible = true;
this.videoWindowProps.playRecord = false;
that.videoWindowProps.title = `实时报警窗口(${data.cameraName}`;
that.videoWindowProps.videoUrl = data.cameraCode; //相机编码
that.videoWindowProps.isAlarm = true;
that.videoWindowProps.visible = true;
that.videoWindowProps.playRecord = false;
this.videoWindowProps.warnEvent.happenTime = data.happenTime;
this.videoWindowProps.warnEvent.happenLoc = `${Number(data.lon).toFixed(6)},${Number(data.lat).toFixed(6)}`;
this.videoWindowProps.warnEvent.warnNum = 1;
this.videoWindowProps.warnEvent.warnLevel = filterDictTextByCache('ms_warn_level', data.warnLevel);
this.videoWindowProps.warnEvent.warnType = filterDictTextByCache('ms_warn_type', data.warnType);
this.videoWindowProps.warnEvent.warnContent = data.warnContent;
that.videoWindowProps.warnEvent.happenTime = data.happenTime;
that.videoWindowProps.warnEvent.happenLoc = `${Number(data.lon).toFixed(6)},${Number(data.lat).toFixed(6)}`;
that.videoWindowProps.warnEvent.warnNum = 1;
that.videoWindowProps.warnEvent.warnLevel = filterDictTextByCache('ms_warn_level', data.warnLevel);
that.videoWindowProps.warnEvent.warnType = filterDictTextByCache('ms_warn_type', data.warnType);
that.videoWindowProps.warnEvent.warnContent = data.warnContent;
//若警示界面打开着,则刷新列表
if ($('.infoList').css('visibility') == 'visible') {
@ -228,19 +236,19 @@ async function websocketonmessage(e) {
}
//提示音
await this.$refs.audio.play();
await that.$refs.audio.play();
setTimeout(() => {
this.$refs.audio.pause(); //N秒后暂停播放
that.$refs.audio.pause(); //N秒后暂停播放
}, 3 * 1000);
} else if (data.cmd == 'earthMap_model_realtime_info') {
console.log(data);
console.log(this.radarAlarmDataMap);
console.log(store.radarAlarmDataMap);
// 雷达轨迹报警数据
const alarmContent = data.content;
if (this.radarAlarmDataMap.has(data.eventSerialNum)) {
if (store.radarAlarmDataMap.has(data.eventSerialNum)) {
// 存在雷达报警数据
let radarAlarmData = this.radarAlarmDataMap.get(data.eventSerialNum);
let radarAlarmData = store.radarAlarmDataMap.get(data.eventSerialNum);
let targetMap = radarAlarmData.target;
if (targetMap.has(data.modelId)) {
// 存在目标数据
@ -313,7 +321,7 @@ async function websocketonmessage(e) {
const updateTime = Date.now();
radarAlarmData.timestamp = updateTime;
// 更新 pin 的时间
let alarm = this.alarmInfoMap.get(data.eventSerialNum);
let alarm = store.alarmInfoMap.get(data.eventSerialNum);
if (alarm) {
alarm.timestamp = updateTime;
}
@ -371,23 +379,23 @@ async function websocketonmessage(e) {
};
let targetMap = new Map();
targetMap.set(data.modelId, target);
this.radarAlarmDataMap.set(data.eventSerialNum, {
store.radarAlarmDataMap.set(data.eventSerialNum, {
target: targetMap,
timestamp: Date.now(),
});
if (!this.alarmInfoMap.has(data.eventSerialNum)) {
if (!store.alarmInfoMap.has(data.eventSerialNum)) {
// 不存在告警信息(小灯或扫描线)时发送
// 事件编号到后台使其重新发送websocket报警数据
await new Promise((r) => setTimeout(r, 500));
if (!this.alarmInfoMap.has(data.eventSerialNum)) {
if (!store.alarmInfoMap.has(data.eventSerialNum)) {
console.log('发送websocket报警数据');
this.loreadAlarmInfo(this.url.sendRadarAlarmByWebSocket, data.eventSerialNum);
loreadAlarmInfo(earthMapUrl.sendRadarAlarmByWebSocket, data.eventSerialNum);
}
}
}
if (this.videoWindowProps.visible) {
this.videoWindowProps.warnEvent.warnNum = this.radarAlarmDataMap.get(data.eventSerialNum).target.size;
if (that.videoWindowProps.visible) {
that.videoWindowProps.warnEvent.warnNum = store.radarAlarmDataMap.get(data.eventSerialNum).target.size;
}
// console.debug('雷达轨迹报警数据', this.radarAlarmDataMap);
} else if (data.cmd == '') {
@ -400,9 +408,9 @@ function websocketclose(e) {
console.log('connection closed (' + e.code + ')');
createMessage.warn('websocket连接已断开', 3);
}
function websocketdosend(configName) {
function websocketdosend(configName,that) {
//发送数据
this.spinning = !this.spinning; //加载状态
that.spinning = !that.spinning; //加载状态
console.log('this.websock[configName]', websock[configName]);
let message = {
topic: 'Show_Single_Video',

2832
src/views/earthMap/edit/EarthComp.vue

File diff suppressed because it is too large
Loading…
Cancel
Save