火星地图引入
1.引入
<div id="centerDiv" class="mapcontainer">
<!-- <mars-map-new v-if="modelType == 'qbjb'" :mapKey="modelType" :url="configUrl" @onload="onload" @getCamera="getCamera"
ref="marsMapNew" /> -->
<mars-map :menuType="menuType" :url="configUrl" @onload="onload" @getCamera="getCamera" ref="marsMap" />
data() {
const basePathUrl = window.basePathUrl || ''
return {
menuType: '', //菜单类型 【情报交班 jiaoban】 【监控 jiankong】
map: null,
flyReviewFlag: true,
addWeixingFlag: true,
lianhuaFlyShow: false,
startRotateFlag: true,
rotateAddFlag: true,
configUrl: basePathUrl + 'config/config.json',
import MarsMap from '@/components/mars-work/mars-map.vue'
config.json
{
"map3d": {
"scene": {
"center": {"lat": 25.751340,"lng":117.753204,
"alt":964141,"heading":360,"pitch":-90},
"scene3DOnly": false,
"shadows": false,
"removeDblClick": true,
"sceneMode": 3,
"showSun": true,
"showMoon": true,
"showSkyBox": true,
"showSkyAtmosphere": true,
"fog": true,
"fxaa": true,
"contextOptions": {"requestWebgl1":true},
"requestRenderMode": true,
"globe": {
"depthTestAgainstTerrain": false,
"baseColor": "#546a53",
"showGroundAtmosphere": true,
"enableLighting": false
},
"cameraController": {
"zoomFactor": 3.0,
"minimumZoomDistance": 1,
"maximumZoomDistance": 50000000,
"enableRotate": true,
"enableTranslate": true,
"enableTilt": true,
"enableZoom": true,
"enableCollisionDetection": true,
"minimumCollisionTerrainHeight": 15000
}
},
"control": {
"homeButton": true,
"baseLayerPicker": true,
"sceneModePicker": true,
"vrButton": false,
"fullscreenButton": true,
"navigationHelpButton": false,
"animation": false,
"timeline": false,
"infoBox": false,
"geocoder": false,
"selectionIndicator": true,
"contextmenu": { "hasDefault": false },
"mouseDownView": false,
"compass": true,
"distanceLegendDesc": "比例尺位置 这是一条注释",
"distanceLegend": { "right": "0px", "bottom": "120px", "z-index": 99
}
},
"terrain": {
"Desc": "地形数据 这是一条注释",
"url": "http://10.18.101.36:8850/gis/chinadem",
"show": true
},
"basemaps": [
{ "id": 10, "name": "地图底图",
"type": "group" },
{
"id": 2021,
"pid": 10,
"name": "天地图影像",
"icon": "img/basemaps/tdt_img.png",
"type": "group",
"layers": [
{ "name": "底图", "type": "tdt", "layer": "img_d" },
{ "name": "注记", "type": "tdt", "layer": "img_z" }
],
"show": true
},
{
"pid": 10,
"name": "天地图电子",
"icon": "img/basemaps/tdt_vec.png",
"type": "group",
"layers": [
{ "name": "底图", "type": "tdt", "layer": "vec_d" },
{ "name": "注记", "type": "tdt", "layer": "vec_z" }
]
},
{
"pid": 10,
"name": "高德影像",
"type": "group",
"icon": "img/basemaps/gaode_img.png",
"layers": [
{ "name": "底图", "type": "gaode", "layer": "img_d" },
{ "name": "注记", "type": "gaode", "layer": "img_z" }
]
},
{
"pid": 10,
"name": "高德电子",
"type": "gaode",
"icon": "img/basemaps/gaode_vec.png",
"layer": "vec"
},
{
"pid": 10,
"name": "ArcGIS影像",
"icon": "img/basemaps/esriWorldImagery.png",
"type": "xyz",
"url": "https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}",
"enablePickFeatures": false
},
{
"pid": 10,
"name": "微软影像",
"icon": "img/basemaps/bingAerial.png",
"type": "bing",
"layer": "Aerial"
},
{
"pid": 10,
"name": "离线地图 (供参考)",
"type": "group",
"icon": "img/basemaps/google_img.png",
"layers": [
{
"name": "全球",
"type": "xyz",
"url": "{dataServer}/tile/googleImg/{z}/{x}/{y}.jpg",
"minimumLevel": 0,
"maximumLevel": 9
},
{
"name": "中国",
"type": "xyz",
"url": "{dataServer}/tile/googleImg/{z}/{x}/{y}.jpg",
"minimumLevel": 10,
"maximumLevel": 12,
"rectangle": { "xmin": 69.706929, "xmax": 136.560941, "ymin": 15.831038, "ymax": 52.558005 }
},
{
"name": "具体项目(如合肥)",
"type": "xyz",
"url": "{dataServer}/tile/googleImg/{z}/{x}/{y}.jpg",
"minimumLevel": 12,
"maximumLevel": 18,
"rectangle": { "xmin": 116.33236, "xmax": 118.183557, "ymin": 31.143784, "ymax": 32.565035 }
}
]
}
]
}
}
/mars-work/mars-map.vue'
<template>
<div :id="`mars3d-container${mapKey}`" class="mars3d-container"></div>
</template>
<script>
import Vue from 'vue'
// 使用免费开源版本
// import 'mars3d-cesium/Build/Cesium/Widgets/widgets.css'
import 'mars3d/dist/mars3d.css'
import * as mars3d from 'mars3d'
import 'mars3d-space'
import { mapUtil } from '@/tool/mapTool'
// let mars3d = window.mars3d
// 导入插件(其他插件类似,插件清单访问:http://mars3d.cn/dev/guide/start/architecture.html)
// echarts插件
// import 'mars3d-echarts'
// 为了方便使用,绑定到原型链,在其他vue文件,直接 this.mars3d 来使用
Vue.prototype.mars3d = mars3d
Vue.prototype.Cesium = mars3d.Cesium
export default {
name: 'mars3dViewer',
props: {
// 地图唯一性标识
mapKey: {
type: String,
default: ''
},
// 初始化配置config.json的地址
url: String,
// 自定义参数
options: Object
},
mounted() {
mars3d.Resource.fetchJson({ url: this.url }).then((data) => {
// 构建地图
this.initMars3d({
...data.map3d,
...this.options
})
})
},
beforeDestroy() {
const map = this[`map${this.mapKey}`]
if (map) {
map.destroy()
delete this[`map${this.mapKey}`]
}
console.log('>>>>> 地图卸载完成 >>>>')
},
methods: {
initMars3d(mapOptions) {
// 创建三维地球场景
var map = new mars3d.Map(`mars3d-container${this.mapKey}`, mapOptions)
this[`map${this.mapKey}`] = map
mapUtil.initMap(map, this)
console.log('>>>>> 地图创建成功 >>>>', map)
// 监听鼠标移动事件
map.on(mars3d.EventType.mouseMove, this.showMouseCoordinates)
// 挂载到全局对象下,所有组件通过 this.map 访问
// Vue.prototype[`map${this.mapKey}`] = map
// 绑定对alert的处理,右键弹出信息更美观。
// window.haoutil = window.haoutil || {}
// window.haoutil.msg = (msg) => {
// this.$message.success(msg)
// }
// window.haoutil.alert = (msg) => {
// this.$message.success(msg)
// }
// 抛出事件
this.$emit('onload', map)
},
showMouseCoordinates(event) {
// 获取鼠标在屏幕上的位置
const windowPosition = event.endPosition
// 转换为笛卡尔空间直角坐标
const cartesian3 = mars3d.PointUtil.getCurrentMousePosition(this.map.scene, windowPosition)
if (cartesian3) {
// 将笛卡尔坐标转换为地理坐标(经纬度)
const position = this.Cesium.Ellipsoid.WGS84.cartesianToCartographic(cartesian3)
// 将坐标格式化为字符串
let lng = this.Cesium.Math.toDegrees(position.longitude).toFixed(6)
let lat = this.Cesium.Math.toDegrees(position.latitude).toFixed(6)
let height = position.height.toFixed(2)
let mars3dLngLat = {
lng: lng,
lat: lat,
height: height
}
this.$parent.$refs.HomeFooter1.mars3dLngLat = mars3dLngLat
console.log(`经度:${lng}° 纬度:${lat}° 高程:${height}米`)
// 更新鼠标位置显示元素的内容
}
}
}
}
</script>
<style lang='less'>
.mars3d-container {
height: 100%;
overflow: hidden;
}
/**cesium 工具按钮栏*/
.cesium-viewer-toolbar {
top: 110px !important;
right: 18px !important;
}
.cesium-toolbar-button img {
height: 100%;
}
.cesium-viewer-toolbar>.cesium-toolbar-button,
.cesium-navigationHelpButton-wrapper,
.cesium-viewer-geocoderContainer {
margin-bottom: 5px;
float: right;
clear: both;
text-align: center;
}
.cesium-button {
background-color: #3f4854;
color: #e6e6e6;
fill: #e6e6e6;
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.3);
line-height: 32px;
float: right;
}
/**cesium 底图切换面板*/
.cesium-baseLayerPicker-dropDown {
bottom: -200px;
right: 40px;
max-height: 700px;
margin-bottom: 5px;
}
/**cesium 帮助面板*/
.cesium-navigation-help {
top: auto;
bottom: 0;
left: 40px;
transform-origin: left bottom;
}
/**cesium 二维三维切换*/
.cesium-sceneModePicker-wrapper {
width: auto;
}
.cesium-sceneModePicker-wrapper .cesium-sceneModePicker-dropDown-icon {
float: right;
margin: 0 3px;
}
/**cesium POI查询输入框*/
.cesium-viewer-geocoderContainer .search-results {
left: 0;
right: 40px;
width: auto;
z-index: 9999;
}
.cesium-geocoder-searchButton {
background-color: #3f4854;
}
.cesium-viewer-geocoderContainer .cesium-geocoder-input {
background-color: rgba(63, 72, 84, 0.7);
}
.cesium-viewer-geocoderContainer .cesium-geocoder-input:focus {
background-color: rgba(63, 72, 84, 0.9);
}
.cesium-viewer-geocoderContainer .search-results {
background-color: #3f4854;
}
/**cesium info信息框*/
.cesium-infoBox {
top: 50px;
background: rgba(63, 72, 84, 0.9);
}
.cesium-infoBox-title {
background-color: #3f4854;
}
/**cesium 任务栏的FPS信息*/
.cesium-performanceDisplay-defaultContainer {
top: auto;
bottom: 35px;
right: 50px;
}
.cesium-performanceDisplay-ms,
.cesium-performanceDisplay-fps {
color: #fff;
}
/**cesium tileset调试信息面板*/
.cesium-viewer-cesiumInspectorContainer {
top: 10px;
left: 10px;
right: auto;
background-color: #3f4854;
}
.cesium-widget {
canvas {
width: 100%;
height: 105%;
touch-action: none;
}
}
</style>
vue。confg。vue的配置文件
const path = require('path')
const webpack = require('webpack')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const NodePolyfillPlugin = require('node-polyfill-webpack-plugin')
module.exports = {
publicPath: '/',
assetsDir: 'static',
outputDir: 'dist',
lintOnSave: false, // 是否开启eslint
productionSourceMap: false, // 不需要生产环境的 source map
filenameHashing: true, // 文件名哈希
// 它支持webPack-dev-server的所有选项
// devServer: {
// host: '0.0.0.0', // 也可以直接写IP地址这样方便真机测试
// port: 3001, // 端口号
// open: true // 配置自动启动浏览器
// },
devServer: {
// host: '0.0.0.0', // 也可以直接写IP地址这样方便真机测试
port: 3001, // 端口号
// open: true, // 配置自动启动浏览器
proxy: {
'/navy': {
// target: 'http://10.18.5.29:9520', // 后台网关地址
target: 'http://10.18.101.36:9520', // 后台网关地址
// ws: false,
changeOrigin: true,
pathRewrite: {
'^/navy': ''
}
},
'/server': {
// target: 'http://10.18.5.29:9520', // 后台网关地址
target: 'http://10.18.101.36:9520', // 后台网关地址
// target: 'http://3.128.124.83:9520', // 后台网关地址
// ws: false,
changeOrigin: true,
pathRewrite: {
'^/server': ''
}
},
}
},
configureWebpack: (config) => {
if (process.env.VUE_APP_MARS3D_SOURCE === 'module') {
const cesiumSourcePath = 'node_modules/mars3d-cesium/Build/Cesium/' // cesium库安装目录
const cesiumRunPath = './mars3d-cesium/' // cesium运行时路径
let plugins = [
// 标识cesium资源所在的主目录,cesium内部资源加载、多线程等处理时需要用到
new webpack.DefinePlugin({
CESIUM_BASE_URL: JSON.stringify(path.join(config.output.publicPath, cesiumRunPath))
}),
// Cesium相关资源目录需要拷贝到系统目录下面(部分CopyWebpackPlugin版本的语法可能没有patterns)
new CopyWebpackPlugin({
patterns: [
{ from: path.join(cesiumSourcePath, 'Workers'), to: path.join(config.output.path, cesiumRunPath, 'Workers') },
{ from: path.join(cesiumSourcePath, 'Assets'), to: path.join(config.output.path, cesiumRunPath, 'Assets') },
{ from: path.join(cesiumSourcePath, 'ThirdParty'), to: path.join(config.output.path, cesiumRunPath, 'ThirdParty') },
{ from: path.join(cesiumSourcePath, 'Widgets'), to: path.join(config.output.path, cesiumRunPath, 'Widgets') }
]
}),
new NodePolyfillPlugin()
]
return {
module: { unknownContextCritical: false }, // 配置加载的模块类型,cesium时必须配置
plugins: plugins
}
} else {
return {
externals: { 'mars3d-cesium': 'Cesium' } //排除使用 mars3d-cesium
}
}
},
css: {
// 启用 CSS modules
// requireModuleExtension: false,
// 是否使用css分离插件
extract: true,
// 开启 CSS source maps,一般不建议开启
sourceMap: false,
// css预设器配置项
loaderOptions: {
sass: {
prependData: '@import "mars3d-cesium/Build/Cesium/Widgets/widgets.css";',
},
},
},
}
mapTOOL.js
import Vue from 'vue'
import { Cesium, name } from 'mars3d'
import moment from 'moment'
let graphicMarkerGate
let graphicLayerPoint //路线规划相关的参数
let graphicGroundDisposal //地面处置相关的参数
let graphicEnemyMarkerGate // 外台军力量标记矢量数据
let graphicProvinceLayer // 战区layer
let graphic // 情报分析graphic
let graphicAirForceLayer // 空军空域
let graphicLayerZD // 阵地
let mapUtil = {
// 初始化地图
initMap(map, that) {
Vue.prototype.mapData = { baseDateLayers: [], layers: [] }//baseDateLayers 里面添加的图层在点击清除全图的时候清除不掉
Vue.prototype.mapData.map = map
map.flyHome({ duration: 0 })
// 开场动画
map.openFlyAnimation({
callback: function() {
// 动画播放完成后回调
}
})
const mars3d = that.mars3d
map.on(mars3d.EventType.click, (event) => {
let point = mars3d.LngLatPoint.fromCartesian(event.cartesian)
that.$emit('getCamera', point)
})
map.on(mars3d.EventType.rightClick, (event) => {//鼠标右击事件
// let point = mars3d.LngLatPoint.fromCartesian(event.cartesian)
// that.$emit('getCamera',point)
})
},
// 卫星
createSatellite(that, arr) {
const mars3d = that.mars3d
let map = that.mapData.map
// 创建矢量数据图层
const graphicLayer = new mars3d.layer.GraphicLayer({ id: 'weixing' })
map.addLayer(graphicLayer)
that.mapData.layers.push(graphicLayer)
// graphicLayer.on(mars3d.EventType.click, function (event) {
// console.log("单击了卫星", event)
// })
// graphicLayer.bindPopup(function (event) {
// const attr = event.graphic.attr || {}
// attr["类型"] = event.graphic.type
// attr["备注"] = "我支持鼠标交互"
// return mars3d.Util.getTemplateHtml({ title: "卫星图层", template: "all", attr })
// })
for (let i = 0; i < arr.length; i += 3) {
const weixin = new mars3d.graphic.Satellite({
name: arr[i],
tle1: arr[i + 1],
tle2: arr[i + 2],
model: {
url: '/model/weixing.gltf',
scale: 1,
minimumPixelSize: 60
},
label: {
text: arr[i],
color: '#ffffff',
opacity: 1,
font_family: '楷体',
font_size: 30,
outline: true,
outlineColor: '#000000',
outlineWidth: 3,
background: true,
backgroundColor: '#000000',
backgroundOpacity: 0.5,
font_weight: 'normal',
font_style: 'normal',
pixelOffsetX: 0,
pixelOffsetY: -20,
scaleByDistance: true,
scaleByDistance_far: 10000000,
scaleByDistance_farValue: 0.4,
scaleByDistance_near: 100000,
scaleByDistance_nearValue: 1
},
path: {
color: '#e2e2e2',
opacity: 0.5,
width: 1
},
highlight: {
path: {
opacity: 1,
width: 2
}
}
})
graphicLayer.addGraphic(weixin)
}
map.setCameraView({ lat: 37.73795, lng: 97.453779, alt: 16492043.7, heading: 360, pitch: -90 })
},
addGraphicLayer(that, graphicLayer) {
const mars3d = that.mars3d
let map = that.mapData.map
let lng = sessionStorage.getItem('lng')
let lat = sessionStorage.getItem('lat')
let id = sessionStorage.getItem('id')
map.setCameraView(
{ 'lat': lat, 'lng': lng, 'alt': 7259.5, 'heading': 0, 'pitch': -90 })
//创建标注点位图层实列
graphicMarkerGate = new mars3d.layer.GraphicLayer({
allowDrillPick: true // 如果存在坐标完全相同的图标点,可以打开该属性,click事件通过graphics判断
})
map.addLayer(graphicMarkerGate)
let markerGate = new mars3d.graphic.BillboardEntity({
id: 'BillboardEntity' + id,
position: [lng, lat, 1000],//坐标点位和高度值
style: {
image: 'img/marker/mark-blue.png',//可自定义点位展示图标,需要要使用变量引用(直接引用可能不生效)
scale: 1,
horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
verticalOrigin: Cesium.VerticalOrigin.BOTTOM
//可配置点位显示的高度范围
// distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
// 0.0,
// 500000,
// ),
// scaleByDistance: new Cesium.NearFarScalar(200000, 1.0, 500000, 0.5),
}
})
graphicMarkerGate.addGraphic(markerGate)
},
removeGraphic() {
let id = sessionStorage.getItem('id')
let diansgraphic = graphicMarkerGate.getGraphicById('BillboardEntity' + id)
diansgraphic && diansgraphic.remove(true)
},
// 删除卫星
removeSatellite(that) {
let map = that.mapData.map
if (map.getLayerById('weixing')) {
map.getLayerById('weixing').remove()
}
},
// 路径规划-多个坐标点
addPlanPath(that, pointArr) {
// console.log('调用了没', pointArr)
const mars3d = that.mars3d
let map = that.mapData.map
let arrList = pointArr[0].points
const firstPoint = arrList[0]
const lastPoint = arrList[arrList.length - 1]
map.setCameraView({ 'lng': arrList[0][0], 'lat': arrList[0][1], 'alt': 20000, 'heading': 0, 'pitch': -90 })
graphicLayerPoint = new mars3d.layer.GraphicLayer()
map.addLayer(graphicLayerPoint)
// 起点图标
const firstGraphic = new mars3d.graphic.BillboardEntity({
id: 'startPoint',
position: new mars3d.LngLatPoint(firstPoint[0], firstPoint[1]),
style: {
image: 'img/marker/qd.png',
scale: 0.75,
horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
clampToGround: true,
highlight: {
scale: 1
}
}
})
graphicLayerPoint.addGraphic(firstGraphic)
// 终点图标
const lastGraphic = new mars3d.graphic.BillboardEntity({
id: 'endPoint',
position: new mars3d.LngLatPoint(lastPoint[0], lastPoint[1]),
style: {
image: 'img/marker/zd.png',
scale: 0.75,
horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
clampToGround: true,
highlight: {
scale: 1
}
}
})
graphicLayerPoint.addGraphic(lastGraphic)
// 路线
const graphic = new mars3d.graphic.PolylineEntity({
id: 'PolylineEntity' + pointArr[0].id,
positions: arrList,
style: {
width: 5,
// color: "#3388ff",
materialType: mars3d.MaterialType.PolylineOutline,
materialOptions: {
color: '#3388ff',
outlineWidth: 2,
outlineColor: '#3388ff'
},
clampToGround: true //是否贴地
},
attr: {
// id: 'PolylineEntity' + pointArr[0].id,
'名称': '示例12'
}
})
graphicLayerPoint.addGraphic(graphic)
},
// 路径规划-清除标记点
removePoints() {
let id = sessionStorage.getItem('ljghId')
let diansgraphic = graphicLayerPoint.getGraphicById('PolylineEntity' + id)
diansgraphic && diansgraphic.remove(true)
let diansgraphicStart = graphicLayerPoint.getGraphicById('startPoint')
diansgraphicStart && diansgraphicStart.remove(true)
let diansgraphicEnd = graphicLayerPoint.getGraphicById('endPoint')
diansgraphicEnd && diansgraphicEnd.remove(true)
},
// removeGraphic(graphic, hasDestroy) {
// graphicLayerPoint.removeGraphic(graphic)
// },
// 添加 情报态势分析
addGraphicTSFX(that, val, index) {
let point = val.point
console.log(point, 'point')
const mars3d = that.mars3d
let map = that.mapData.map
// 先删除上一次的划线
if (map.getLayerById('TSFXLayer')) {
map.getLayerById('TSFXLayer').remove()
}
graphicLayerPoint = new mars3d.layer.GraphicLayer({ id: 'TSFXLayer' })
map.addLayer(graphicLayerPoint)
map.setCameraView({ 'lng': point[0][0], 'lat': point[0][1], 'alt': 300000, 'heading': 300, 'pitch': -90 })
graphic = new mars3d.graphic.PolylineEntity({
id: 'index' + index,
positions: point,
style: {
width: 5,
color: index == 1 ? '#3388ff' : 'red',
}
})
graphicLayerPoint.addGraphic(graphic)
const firstPoint = point[0]
const lastPoint = point[point.length - 1]
const zjPoint = point.slice(1, -1)
// 起点图标
const firstGraphic = new mars3d.graphic.BillboardEntity({
id: 'startPoint',
position: [firstPoint[0], firstPoint[1], firstPoint[2]],
style: {
image: 'img/marker/qd.png',
scale: 0.75,
horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
// clampToGround: true,
highlight: {
scale: 1
},
label: {
text: `${firstPoint[3]}`,
font_size: 14,
color: "#ffffff",
pixelOffsetY: -10,
distanceDisplayCondition: true,
distanceDisplayCondition_far: 500000,
distanceDisplayCondition_near: 0
}
}
})
graphicLayerPoint.addGraphic(firstGraphic)
// 终点图标
const lastGraphic = new mars3d.graphic.BillboardEntity({
id: 'endPoint',
position: [lastPoint[0], lastPoint[1], lastPoint[2]],
style: {
image: 'img/marker/zd.png',
scale: 0.75,
horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
highlight: {
scale: 1
},
label: {
text: `${lastPoint[3]}`,
font_size: 14,
color: "#ffffff",
pixelOffsetY: -10,
distanceDisplayCondition: true,
distanceDisplayCondition_far: 500000,
distanceDisplayCondition_near: 0
}
}
})
graphicLayerPoint.addGraphic(lastGraphic)
zjPoint.forEach(zj => {
// console.log(zj)
// 中间图标
const lastGraphic = new mars3d.graphic.PointEntity({
id: zj.id,
position: [zj[0], zj[1], zj[2]],
style: {
color: '#ffd500',
pixelSize: 10,
outline: true,
outlineColor: '#ffffff',
outlineWidth: 2,
label: {
text: `${zj[3]}`,
font_size: 14,
color: "#ffffff",
pixelOffsetY: -10,
distanceDisplayCondition: true,
distanceDisplayCondition_far: 500000,
distanceDisplayCondition_near: 0
}
},
})
graphicLayerPoint.addGraphic(lastGraphic)
})
const property = new Cesium.SampledPositionProperty()
property.forwardExtrapolationType = Cesium.ExtrapolationType.HOLD
let start
let stop
for (let i = 0, len = point.length; i < len; i++) {
const item = point[i]
const lng = item[0] // 经度
const lat = item[1] // 纬度
const height = item[2] // 高度
let time = item[3]
let position = null
if (lng && lat) {
position = Cesium.Cartesian3.fromDegrees(lng, lat, height)
}
let juliaDate = null
if (time) {
juliaDate = Cesium.JulianDate.fromIso8601(time)
}
if (position && juliaDate) {
property.addSample(juliaDate, position)
}
if (i === 0) {
start = juliaDate
} else if (i === len - 1) {
stop = juliaDate
}
}
// 设置时钟属性
map.clock.startTime = start.clone()
map.clock.stopTime = stop.clone()
map.clock.currentTime = start.clone()
map.clock.clockRange = Cesium.ClockRange.LOOP_STOP
map.clock.multiplier = 5
// 创建path对象
let pathEntity = new mars3d.graphic.PathEntity({
position: property,
orientation: new Cesium.VelocityOrientationProperty(property),
style: {
resolution: 1,
leadTime: 0,
trailTime: 3600,
color: '#ffd500',
width: 5,
},
label: {
text: `${val.fjType}`,
font_size: 19,
font_family: "楷体",
color: Cesium.Color.AZURE,
outline: true,
visibleDepth: false,
outlineColor: Cesium.Color.BLACK,
outlineWidth: 2,
horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
pixelOffset: new Cesium.Cartesian2(10, -25) // 偏移量
},
model: {
url: '/model/boyin.glb',
scale: 1,
minimumPixelSize: 60
},
})
graphicLayerPoint.addGraphic(pathEntity)
},
// 删除 情报态势分析
removeGraphicTSFX(that){
let map = that.mapData.map
if (map.getLayerById('TSFXLayer')) {
map.getLayerById('TSFXLayer').remove()
}
},
// 地面处置-底层矢量图层
addGroundDisposal(that, positionsArr, idx, fromGjyc) {
// console.log('调用了',positionsArr);
const mars3d = that.mars3d
let map = that.mapData.map
if(!fromGjyc){
map.setCameraView({ 'lng': positionsArr[0][0], 'lat': positionsArr[0][1], 'alt': 800000, 'heading': 0, 'pitch': -90 })
}
// 矢量数据图层 实例创建
graphicGroundDisposal = new mars3d.layer.GraphicLayer()
map.addLayer(graphicGroundDisposal)
const graphic = new mars3d.graphic.PolygonEntity({
id: 'GroundDisposal',
positions: positionsArr,
style: {
color: '#eeeeee',
opacity: 0.5
},
attr: { 'name': 'GroundDisposal' }
})
graphicGroundDisposal.addGraphic(graphic) // 还可以另外一种写法: graphic.addTo(graphicLayer)
},
// 地面处置-清除图层
removeGroundDisposal() {
let diansgraphicGround = graphicGroundDisposal.getGraphicById('GroundDisposal')
diansgraphicGround && diansgraphicGround.remove(true)
},
// 飞机飞行轨迹
fly(that) {
const mars3d = that.mars3d
const Cesium = that.mars3d.Cesium
let map = that.mapData.map
that.mapData.flyObj = {
pathEntity: '',
myLayer: ''
}
// 创建矢量数据图层
let graphicLayer = new mars3d.layer.GraphicLayer({ id: 'fly' })
that.mapData.flyObj.myLayer = graphicLayer
map.addLayer(graphicLayer)
that.mapData.layers.push(graphicLayer)
mars3d.Util.fetchJson({ url: '/model/data/flypath.json' })
.then(function(data) {
const property = new Cesium.SampledPositionProperty()
property.forwardExtrapolationType = Cesium.ExtrapolationType.HOLD
let start
let stop
for (let i = 0, len = data.length; i < len; i++) {
const item = data[i]
const lng = Number(item.x.toFixed(6)) // 经度
const lat = Number(item.y.toFixed(6)) // 纬度
const height = item.z // 高度
const time = item.time // 时间
let position = null
if (lng && lat) {
position = Cesium.Cartesian3.fromDegrees(lng, lat, height)
}
let juliaDate = null
if (time) {
juliaDate = Cesium.JulianDate.fromIso8601(time)
}
if (position && juliaDate) {
property.addSample(juliaDate, position)
}
if (i === 0) {
start = juliaDate
} else if (i === len - 1) {
stop = juliaDate
}
const graphic = new mars3d.graphic.PointPrimitive({
position,
style: {
pixelSize: 4,
color: '#cccccc'
},
popup: '编号:' + item.id + '<br/>时间:' + time
})
graphicLayer.addGraphic(graphic)
}
// 设置时钟属性
map.clock.startTime = start.clone()
map.clock.stopTime = stop.clone()
map.clock.currentTime = start.clone()
map.clock.clockRange = Cesium.ClockRange.LOOP_STOP
map.clock.multiplier = 5
// 创建path对象
let pathEntity = new mars3d.graphic.PathEntity({
position: property,
orientation: new Cesium.VelocityOrientationProperty(property),
style: {
resolution: 1,
leadTime: 0,
trailTime: 3600,
color: '#ff0000',
width: 3
},
label: {
text: '飞机1号',
font_size: 19,
font_family: '楷体',
color: Cesium.Color.AZURE,
outline: true,
visibleDepth: false,
outlineColor: Cesium.Color.BLACK,
outlineWidth: 2,
horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
pixelOffset: new Cesium.Cartesian2(10, -25) // 偏移量
},
model: {
url: '/model/wrj.glb',
scale: 0.1,
minimumPixelSize: 20
},
popup: '飞行1号'
})
that.mapData.flyObj.pathEntity = pathEntity
graphicLayer.addGraphic(pathEntity)
})
.catch(function(error) {
console.log('加载JSON出错', error)
})
},
// 飞机飞行视角
flyView(that, type) {
let map = that.mapData.map
let pathEntity = that.mapData.flyObj.pathEntity
if (type == 'viewAircraft') { // 跟踪视角
map.trackedEntity = pathEntity.entity
pathEntity.flyToPoint({
radius: 500, // 距离目标点的距离
heading: 40,
pitch: -50,
duration: 0.01
})
} else if (type == 'viewTopDown') { //上方视角
map.trackedEntity = undefined
map.flyToPoint(pathEntity.positionShow, {
radius: 2000,
heading: -90,
pitch: -89
})
} else if (type == 'viewSide') { //侧方视角
map.trackedEntity = undefined
map.flyToPoint(pathEntity.positionShow, {
radius: 3000,
heading: -90,
pitch: -25
})
}
},
//花莲机场视角
hualianAirport(that) {
let map = that.mapData.map
map.setCameraView({ lat: 23.999568, lng: 121.638045, alt: 3582.4, heading: 308.5, radius: 4000, pitch: -42.4 })
},
// 删除飞机飞行轨迹
removeFly(that) {
let map = that.mapData.map
const Cesium = that.mars3d.Cesium
if (map.getLayerById('fly')) {
map.getLayerById('fly').remove()
}
map.clock.startTime = Cesium.JulianDate.fromDate(new Date())
map.clock.stopTime = Cesium.JulianDate.fromDate(new Date(new Date().getTime() + 24 * 60 * 60 * 1000))
map.clock.currentTime = Cesium.JulianDate.fromDate(new Date())
map.clock.clockRange = Cesium.ClockRange.UNBOUNDED
map.clock.multiplier = 1
},
// 情报态势飞机轨迹
updateFlyData(that, dataList, html, collbackData, obj, flag) {
const mars3d = that.mars3d
let map = that.mapData.map
if (flag) {//点击按钮之后强行重新加载
delete that.mapData.updateFlyData
}
const Cesium = that.mars3d.Cesium
const lnglats = []
// // // 创建矢量数据图层
if (map.getLayerById('updateFlyData') && that.mapData.updateFlyData) {
for (const key in dataList) {
if (obj.flag && collbackData.flyNum == key) {
obj.lnglats.push([dataList[key].ln, dataList[key].la, dataList[key].h])
if (map.getLayerById(collbackData.flyNum + 'box')) {
let graphicLayerbox = map.getLayerById(collbackData.flyNum + 'box')
let graphicbox = map.getLayerById(collbackData.flyNum + 'box').getGraphicById(collbackData.flyNum + 'BoxEntity')
graphicbox.remove()
let heding = dataList[key].c
const boxs = new mars3d.graphic.BoxEntity({
id: collbackData.flyNum + 'BoxEntity',
position: [dataList[key].ln, dataList[key].la, dataList[key].h],
style: {
dimensions: new Cesium.Cartesian3(300000.0, 40000.0, 1200.0),
heading: heding - 90,
fill: true,
color: '#00ff00',
opacity: 0.4
}
// attr: { remark: "示例1" }
})
graphicLayerbox.addGraphic(boxs)
}
}
if (that.mapData.updateFlyData.updateFlyDataList[key]) {
let graphic = that.mapData.updateFlyData.myLayer.getGraphicById(key)
if (graphic.isPrivate) {
return
}
graphic.addDynamicPosition(Cesium.Cartesian3.fromDegrees(dataList[key].ln, dataList[key].la, dataList[key].h), moment(new Date(new Date().getTime() + 5400)).format('YYYY-MM-DD HH:mm:ss'))
delete that.mapData.updateFlyData.updateFlyDataList[key]
} else {
let url = ''
switch (dataList[key].jx1) {
case '大型机':
url = '/model/boyin.glb'
break
case '导弹':
url = '/model/feiji.glb'
break
case '直升机':
url = '/model/feiji.glb'
break
case '小型机':
url = '/model/zhandouji.glb'
break
default:
url = '/model/feiji.glb'
break
}
const graphic = new mars3d.graphic.ModelPrimitive({
// forwardExtrapolationType: Cesium.ExtrapolationType.HOLD,
style: {
url: url,
scale: 0.5,
heading: dataList[key].c - 90,
minimumPixelSize: 45,
silhouette: true,
silhouetteColor: dataList[key].color ? dataList[key].color : 'rgba(255,173,0,1)',
silhouetteSize: 1,
// 高亮时的样式(默认为鼠标移入,也可以指定type:'click'单击高亮),构造后也可以openHighlight、closeHighlight方法来手动调用
highlight: {
type: mars3d.EventType.click,
silhouette: true,
silhouetteColor: '#ff0000',
silhouetteSize: 4
},
label: {
// 不需要文字时,去掉label配置即可
text: dataList[key].p,
font_size: 12,
color: '#00ff00',
pixelOffsetY: -20,
outline: true,
outlineColor: '#000000',
distanceDisplayCondition: true,
distanceDisplayCondition_near: 50
}
},
id: key,
attr: {
index: key,
name: 'ModelPrimitive',
ecdm: dataList[key].ecdm,
oil: dataList[key].oil,
lng: dataList[key].ln,
lat: dataList[key].la,
height: dataList[key].h,
heading: dataList[key].c,
id: key,
v: dataList[key].v,
ta: dataList[key].ta,
jx1: dataList[key].jx1
}
})
graphic.bindPopup(html)
graphic.addDynamicPosition(Cesium.Cartesian3.fromDegrees(dataList[key].ln, dataList[key].la, dataList[key].h), moment(new Date()).format('YYYY-MM-DD HH:mm:ss'))
graphic.addDynamicPosition(Cesium.Cartesian3.fromDegrees(dataList[key].ln, dataList[key].la, dataList[key].h), moment(new Date(new Date().getTime() + 5400)).format('YYYY-MM-DD HH:mm:ss'))
that.mapData.updateFlyData.myLayer.addGraphic(graphic)
}
}
for (const key in that.mapData.updateFlyData.updateFlyDataList) {
let graphic = that.mapData.updateFlyData.myLayer.getGraphicById(key)
graphic.remove()
delete that.mapData.updateFlyData.updateFlyDataList[key]
}
that.mapData.updateFlyData.updateFlyDataList = dataList
} else {
if (that.mapData.updateFlyData) {
return
}
let graphicLayer = new mars3d.layer.GraphicLayer({
id: 'updateFlyData'
})
map.addLayer(graphicLayer)
that.mapData.layers.push(graphicLayer)
// 在layer上绑定监听事件
graphicLayer.on(mars3d.EventType.click, function(event) {
obj.flag = true
collbackData.flyNum = event.id
collbackData.attr = event.graphic.options.attr
if (collbackData.options) {
collbackData.options = event.graphic.options
}
console.log('监听layer,单击了矢量对象', event)
})
that.mapData.updateFlyData = {
myLayer: graphicLayer,
updateFlyDataList: dataList
}
for (const key in dataList) {
let url = ''
switch (dataList[key].jx1) {
case '大型机':
url = '/model/boyin.glb'
break
case '导弹':
url = '/model/boyin.glb'
break
case '直升机':
url = '/model/boyin.glb'
break
case '小型机':
url = '/model/boyin.glb'
break
default:
url = '/model/boyin.glb'
break
}
const graphic = new mars3d.graphic.ModelPrimitive({
// forwardExtrapolationType: Cesium.ExtrapolationType.HOLD,
style: {
url: url,
scale: 110.5,
heading: dataList[key].c - 90,
minimumPixelSize: 45,
silhouette: true,
silhouetteColor: dataList[key].color ? dataList[key].color : 'rgba(255,173,0,1)',
silhouetteSize: 1,
// 高亮时的样式(默认为鼠标移入,也可以指定type:'click'单击高亮),构造后也可以openHighlight、closeHighlight方法来手动调用
highlight: {
type: mars3d.EventType.click,
silhouette: true,
silhouetteColor: '#ff0000',
silhouetteSize: 4
},
label: {
// 不需要文字时,去掉label配置即可
text: dataList[key].p,
font_size: 13,
color: '#00ff00',
outline: true,
outlineColor: '#000000',
pixelOffsetY: -20,
distanceDisplayCondition: true,
distanceDisplayCondition_near: 50
}
},
id: key,
attr: {
index: key,
name: 'ModelPrimitive',
ecdm: dataList[key].ecdm,
oil: dataList[key].oil,
lng: dataList[key].ln,
lat: dataList[key].la,
height: dataList[key].h,
heading: dataList[key].c,
id: key,
v: dataList[key].v,
ta: dataList[key].ta,
jx1: dataList[key].jx1
}
})
graphic.bindPopup(html)
let point = Cesium.Cartesian3.fromDegrees(dataList[key].ln, dataList[key].la, dataList[key].h)
graphicLayer.addGraphic(graphic)
graphic.addDynamicPosition(point, moment(new Date()).format('YYYY-MM-DD HH:mm:ss'))
graphic.addDynamicPosition(point, moment(new Date(new Date().getTime() + 5400)).format('YYYY-MM-DD HH:mm:ss'))
}
}
},
addmodeltest(that) {
const mars3d = that.mars3d
let map = that.mapData.map
const Cesium = that.mars3d.Cesium
// let graphicLayer = new mars3d.layer.GraphicLayer({
// id: "updateFlyData"
// })
// map.addLayer(graphicLayer)
// 创建矢量数据图层
let graphicLayer = new mars3d.layer.GraphicLayer()
map.addLayer(graphicLayer)
for (let i = 0; i < 400; i++) {
const graphic = new mars3d.graphic.ModelPrimitive({
// forwardExtrapolationType: Cesium.ExtrapolationType.HOLD,
style: {
url: '/model/boyin.glb',
scale: 0.5,
minimumPixelSize: 20,
// 高亮时的样式(默认为鼠标移入,也可以指定type:'click'单击高亮),构造后也可以openHighlight、closeHighlight方法来手动调用
highlight: {
type: mars3d.EventType.click,
silhouette: true,
silhouetteColor: '#ff0000',
silhouetteSize: 4
},
label: {
// 不需要文字时,去掉label配置即可
text: '皖A000' + i,
font_size: 16,
color: '#ffffff',
outline: true,
outlineColor: '#000000',
pixelOffsetY: -20,
distanceDisplayCondition: true,
distanceDisplayCondition_far: 50000,
distanceDisplayCondition_near: 0
}
},
attr: { index: i, name: 'ModelPrimitive' }
})
graphicLayer.addGraphic(graphic)
}
// 设置动态位置
changePosition(0)
// 定时更新动态位置(setInterval为演示)
const interval = 3
changePosition(interval)
setInterval(() => {
changePosition(interval)
}, interval * 1000)
// 改变位置
function changePosition(time) {
graphicLayer.eachGraphic((graphic) => {
if (graphic.isPrivate) {
return
}
graphic.addDynamicPosition(randomPoint(), time) // 按time秒运动至指定位置
})
}
// 取区域内的随机点
function randomPoint() {
const jd = random(110.207666 * 1000, 120.287241 * 1000) / 1000
const wd = random(20.817099 * 1000, 36.876848 * 1000) / 1000
return Cesium.Cartesian3.fromDegrees(jd, wd, 5000)
}
function random(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min)
}
},
showMaxmodelDemo(that) {
let tiles3dLayerAll
let tiles3dLayerFeiji
const mars3d = that.mars3d
const Cesium = that.mars3d.Cesium
let map = that.mapData.map
map.setCameraView(
{
lat: 23.999568, lng: 121.638045, alt: 3582.4,
heading: 308.5, radius: 4000, pitch: -42.4
})
setTimeout(() => {
function removeLayer() {
if (tiles3dLayerAll) {
map.basemap = 2021 // 切换到默认影像底图
map.removeLayer(tiles3dLayerAll, true)
tiles3dLayerAll = null
}
}
removeLayer()
tiles3dLayerAll = new mars3d.layer.TilesetLayer({
name: '花莲机场',
// url: 'http://3.128.126.97:9566/moxing/hualian/all/tileset.json',
url: 'http://10.18.101.36:8850/moxing/hualian/all/tileset.json?token=mars3d',
position: { 'lat': 24.024011, 'lng': 121.618200, alt: 20 },
maximumScreenSpaceError: 1,
highlightEnable: true,
luminanceAtZenith: 0.5,
// highlight:{
// type:'click',
// outlineEffect:true,
// color:"#0f0",
// width:6
// },
cacheBytes: 1073741824, // 1024MB = 1024*1024*1024
maximumCacheOverflowBytes: 2147483648, // 2048MB = 2048*1024*1024
dynamicScreenSpaceError: true,
cullWithChildrenBounds: false,
skipLevelOfDetail: true,
lightColor: new Cesium.Cartesian3(10.0, 10.0, 10.0),
scale: 1,
preferLeaves: true,
// center: { lat: 23.999568, lng:121.638045, alt: 3582.4, heading: 308.5, radius: 4000,pitch: -42.4 },
queryParameters: {
// 可以传自定义url参数,如token等
token: 'mars3d'
},
enableDebugWireframe: true, // 是否可以进行三角网的切换显示
flyTo: true
})
map.addLayer(tiles3dLayerAll)
// 可以绑定Popup弹窗,回调方法中任意处理
tiles3dLayerAll.bindPopup(function (event) {
const attr = event.graphic.attr
// attr["视频"] = `<video src='http://data.mars3d.cn/file/video/lukou.mp4' controls autoplay style="width: 300px;" ></video>`;
return mars3d.Util.getTemplateHtml({ title: attr.name, template: attr.name, attr })
})
// 单击事件
tiles3dLayerAll.on(mars3d.EventType.click, function (event) {
const attr = event.graphic.attr
that.airPortObj.show = !that.airPortObj.show
that.airPortObj.flag = 'hzl'
that.airPortObj.name = attr.name
})
// function removeLayer() {
// if (tiles3dLayerAll) {
// map.basemap = 2021 // 切换到默认影像底图
// map.removeLayer(tiles3dLayerAll, true)
// tiles3dLayerAll = null
// }
// }
// removeLayer()
tiles3dLayerFeiji = new mars3d.layer.TilesetLayer({
name: '花莲机场-飞机',
url: 'http://10.18.101.36:8850/moxing/hualian/feiji/tileset.json',
position: { 'lat': 24.025011, 'lng': 121.617100, alt: 20 },
maximumScreenSpaceError: 1,
cacheBytes: 1073741824, // 1024MB = 1024*1024*1024
maximumCacheOverflowBytes: 2147483648, // 2048MB = 2048*1024*1024
dynamicScreenSpaceError: true,
cullWithChildrenBounds: false,
highlightEnable: true,
// highlight:{
// type:'click',
// outlineEffect:true,
// color:"#0f0",
// width:6
// },
luminanceAtZenith: 0.3,
lightColor: new Cesium.Cartesian3(10.0, 10.0, 10.0),
skipLevelOfDetail: true,
scale: 1,
preferLeaves: true,
// center: { lat: 23.999568, lng:121.638045, alt: 3582.4, heading: 308.5, radius: 4000,pitch: -42.4 },
queryParameters: {
// 可以传自定义url参数,如token等
token: 'mars3d'
},
enableDebugWireframe: true, // 是否可以进行三角网的切换显示
flyTo: true
})
map.addLayer(tiles3dLayerFeiji)
// 添加描边
// 可以绑定Popup弹窗,回调方法中任意处理
tiles3dLayerFeiji.bindPopup(function (event) {
const attr = event.graphic.attr
// attr["视频"] = `<video src='http://data.mars3d.cn/file/video/lukou.mp4' controls autoplay style="width: 300px;" ></video>`;
return mars3d.Util.getTemplateHtml({
title: attr.name
// attr: attr
})//{ title: attr.name, template: attr.name, attr }
})
// 单击事件
tiles3dLayerFeiji.on(mars3d.EventType.click, function (event) {
const attr = event.graphic.attr
that.airPortObj.show = !that.airPortObj.show
that.airPortObj.flag = 'fj'
that.airPortObj.name = attr.name
})
}, 4000)
},
// 清除态势飞机轨迹
removeUpdateFlyData(that) {
let map = that.mapData.map
if (map.getLayerById('updateFlyData')) {
map.getLayerById('updateFlyData').remove()
}
},
// 地图切换
changeBaseLayer(that, layidname, flag) {
// that.mapData.map.basemap = type
that.mapData.map.basemap.getLayer(layidname, 'name').show = flag
},
// 添加去除标注
changeBaseLayerLable(that, flag) {
// that.mapData.map.basemap.getLayer('lable', 'name').show = flag
},
// 清除全图
removeAll(that) {
let map = that.mapData.map
let list = map.getLayers({
basemaps: false,
layers: true
})
console.log(list)
// that.mars3d.layer.GraphicLayer.clear()
// that.mapData.baseDateLayers.graphicLayer.clear()
let Cesium = that.Cesium
map.clock.startTime = Cesium.JulianDate.fromDate(new Date())
map.clock.stopTime = Cesium.JulianDate.fromDate(new Date(new Date().getTime() + 24 * 60 * 60 * 1000))
map.clock.currentTime = Cesium.JulianDate.fromDate(new Date())
map.clock.clockRange = Cesium.ClockRange.UNBOUNDED
map.clock.multiplier = 1
for (const layer of that.mapData.layers) {
layer.remove()
}
for (const layer of list.slice(2)) {
layer.remove()
}
},
// 原点旋转漫游
rotateAdd(that) {
let map = that.mapData.map
const mars3d = that.mars3d
if (that.mapData.rotatePoint) {
this.startRotateAdd(that)
} else {
let rotatePoint = new mars3d.thing.RotatePoint({
direction: false, // 方向 true逆时针,false顺时针
time: 50 // 给定飞行一周所需时间(单位 秒),控制速度
// autoStopAngle: 360, //到达指定角度后自动停止
})
map.addThing(rotatePoint)
// 开启旋转
rotatePoint.start()
that.mapData.rotatePoint = rotatePoint
}
},
startRotateAdd(that) {
let map = that.mapData.map
// 获取当前视角
const point = map.getCenter()
that.mapData.rotatePoint.start(point) // 可以传指定的中心点坐标
},
stopRotateAdd(that) {
that.mapData.rotatePoint.stop()
},
// 重置视角
resetRotate(that) {
let map = that.mapData.map
map.setCameraView({ lat: 37.73795, lng: 97.453779, alt: 8492043.7, heading: 360, pitch: -90 })
},
// 全球漫游
startRotate(that) {
let map = that.mapData.map
const mars3d = that.mars3d
map.setCameraView({ lat: 37.73795, lng: 97.453779, alt: 50000000, heading: 360, pitch: -90 }, {
complete: () => {
let previousTime = ''
this.stopRotate(that)
previousTime = map.clock.currentTime.secondsOfDay
that.mapData.previousTime = previousTime
map.on(mars3d.EventType.clockTick, this.map_onClockTick, that)
}
})
},
stopRotate(that) {
let map = that.mapData.map
const mars3d = that.mars3d
map.off(mars3d.EventType.clockTick, this.map_onClockTick, that)
},
map_onClockTick() {
let map = this.mapData.map
let Cesium = this.Cesium
const spinRate = 100
const currentTime = map.clock.currentTime.secondsOfDay
const delta = (currentTime - this.mapData.previousTime) / 1000
this.mapData.previousTime = currentTime
map.scene.camera.rotate(Cesium.Cartesian3.UNIT_Z, -spinRate * delta)
},
// 战区边界
bonder(that, latlngs, opt = {}, c) {
let { name, id } = opt
const mars3d = that.mars3d
let map = that.mapData.map
let graphicLayer
let color = c ? zchjlinecolor(c) : '#ff0000'
if (map.getLayerById('bonder')) {
graphicLayer = map.getLayerById('bonder')
} else {
graphicLayer = new mars3d.layer.GraphicLayer({ id: 'bonder' })
map.addLayer(graphicLayer)
that.mapData.baseDateLayers.push(graphicLayer)
}
const graphic = new mars3d.graphic.PolylineEntity({
positions: latlngs,
id: id,
style: {
width: 1.5,
color: color
// pixelSize: 10,
// outline:true,
// outlineColor:'#fff',
// outerWidth:2
}
})
graphicLayer.addGraphic(graphic)
function zchjlinecolor(lineColorname) {
if (lineColorname == '白色') {
// return '#fff';
return 'rgba(255, 255, 255,1)'
} else if (lineColorname == '蓝紫色') {
// return '#4d33ae';
return 'rgba(77, 51, 174,1)'
} else if (lineColorname == '浅橙色') {
// return '#fada9b';
return 'rgba(250, 218, 155,1)'
} else if (lineColorname == '深橙色') {
// return '#8a5c01';
return 'rgba(138,92,1,1)'
} else if (lineColorname == '深青色') {
// return '#076565';
return 'rgba(7, 101, 101,1)'
} else if (lineColorname == '血青色') {
// return '#c532e5';
return 'rgba(197, 50, 229,1)'
} else if (lineColorname == '橙色') {
// return '#f7ac16';
return 'rgba(247, 172, 22,1)'
} else if (lineColorname == '粉红色') {
// return '#fed0d0';
return 'rgba(254, 208, 208,1)'
} else if (lineColorname == '黑色') {
// return '#000';
return 'rgba(0,0,0,1)'
} else if (lineColorname == '红色') {
// return '#ff0000';
return 'rgba(255, 0, 0,1)'
} else if (lineColorname == '黄绿色') {
// return '#a0da2d';
return 'rgba(160, 218, 45,1)'
} else if (lineColorname == '灰色') {
// return '#787878';
return 'rgba(120, 120, 120,1)'
} else if (lineColorname == '咖啡色') {
// return '#653e3e';
return 'rgba(101, 62, 62,1)'
} else if (lineColorname == '蓝色') {
// return '#1b39cd';
return 'rgba(27, 57, 205,1)'
} else if (lineColorname == '浅紫色') {
// return '#dabfef';
return 'rgba(218, 191, 239,1)'
} else if (lineColorname == '青色') {
// return '#2bf2f2';
return 'rgba(43, 242, 242,1)'
} else if (lineColorname == '深红色') {
// return '#9b0f0f';
return 'rgba(155, 15, 15,1)'
} else if (lineColorname == '深黄色') {
// return '#f6b93e';
return 'rgba(246, 185, 62,1)'
} else if (lineColorname == '深紫色') {
// return '#8d12bd';
return 'rgba(141, 18, 189,1)'
} else if (lineColorname == '紫色') {
// return '#c532e5';
return 'rgba(197, 50, 229,1)'
} else if (lineColorname == '黄色') {
// return '#ffff0f';
return 'rgba(255, 255, 15,1)'
} else if (lineColorname == '浅灰色') {
// return '#c1c1c1';
return 'rgba(193, 193, 193,1)'
} else if (lineColorname == '浅蓝色') {
// return '#a9b5f0';
return 'rgba(169, 181, 240,1)'
} else if (lineColorname == '绿色') {
// return '#14ec14';
return 'rgba(20, 236, 20,1)'
} else if (lineColorname == '深灰色') {
// return '#474747';
return 'rgba(71, 71, 71,1)'
} else if (lineColorname == '亮青色') {
// return '#6cf2ea';
return 'rgba(108, 242, 234,1)'
} else if (lineColorname == '浅绿色') {
// return '#b2f7b2';
return 'rgba(178, 247, 178,1)'
} else if (lineColorname == '深绿色') {
// return '#117011';
return 'rgba(17, 112, 17,1)'
} else if (lineColorname == '深咖啡色') {
// return '#441f1f';
return 'rgba(68, 31, 31,1)'
} else if (lineColorname == '浅红色') {
// return '#f49c9c';
return 'rgba(244, 156, 156,1)'
} else if (lineColorname == '浅青色') {
// return '#c8f4f1';
return 'rgba(200, 244, 241,1)'
} else {
// return '#ff0000';
return 'rgba(255, 0, 0,1)'
}
}
},
// 移除边界
removeBonder(that, id) {
let map = that.mapData.map
if (map.getLayerById('bonder').getGraphicById(id)) {
map.getLayerById('bonder').getGraphicById(id).remove()
}
},
// 循环删除边界
removeBonders(that, arr) {
let map = that.mapData.map
arr.forEach((v) => {
if (map.getLayerById('bonder').getGraphicById(v)) {
map.getLayerById('bonder').getGraphicById(v).remove()
}
})
},
// 移除popup弹窗
removePopUp(that) {
that.mapData.map.closePopup()
},
// 添加右键功能
bindLayerContextMenu() {
graphicLayer.bindContextMenu([
{
text: '开始编辑对象',
icon: 'fa fa-edit',
show: function (e) {
const graphic = e.graphic
if (!graphic || !graphic.hasEdit) {
return false
}
return !graphic.isEditing
},
callback: (e) => {
const graphic = e.graphic
if (!graphic) {
return false
}
if (graphic) {
graphicLayer.startEditing(graphic)
}
}
},
{
text: '停止编辑对象',
icon: 'fa fa-edit',
show: function (e) {
const graphic = e.graphic
if (!graphic || !graphic.hasEdit) {
return false
}
return graphic.isEditing
},
callback: (e) => {
const graphic = e.graphic
if (!graphic) {
return false
}
if (graphic) {
graphic.stopEditing()
}
}
},
{
text: '删除对象',
icon: 'fa fa-trash-o',
show: (event) => {
const graphic = event.graphic
if (!graphic || graphic.isDestroy) {
return false
} else {
return true
}
},
callback: (e) => {
const graphic = e.graphic
if (!graphic) {
return
}
const parent = graphic.parent // 右击是编辑点时
graphicLayer.removeGraphic(graphic)
if (parent) {
graphicLayer.removeGraphic(parent)
}
}
},
{
text: '计算周长',
icon: 'fa fa-medium',
callback: (e) => {
const graphic = e.graphic
const strDis = mars3d.MeasureUtil.formatDistance(graphic.distance)
globalAlert('该对象的周长为:' + strDis)
}
},
{
text: '计算面积',
icon: 'fa fa-reorder',
callback: (e) => {
const graphic = e.graphic
const strArea = mars3d.MeasureUtil.formatArea(graphic.area)
globalAlert('该对象的面积为:' + strArea)
}
}
])
},
//获取飞机航线轨迹
getflyline(that, arre) {
let map = that.mapData.map
map.flyToPoint([arre.lng, arre.lat, arre.height], { radius: 800000, heading: 350.4, pitch: -43.8 })
let Cesium = that.Cesium
const mars3d = that.mars3d
let graphicLayer = new mars3d.layer.GraphicLayer({
id: arre.id + 'box'
})
map.addLayer(graphicLayer)
that.mapData.layers.push(graphicLayer)
let heding = arre.heading
const graphic = new mars3d.graphic.BoxEntity({
id: arre.id + 'BoxEntity',
position: [arre.lng, arre.lat, arre.height],
style: {
dimensions: new Cesium.Cartesian3(300000.0, 40000.0, 1200.0),
heading: heding - 90,
fill: true,
color: '#00ff00',
opacity: 0.4
}
// attr: { remark: "示例1" }
})
graphicLayer.addGraphic(graphic)
},
removebox(that, attr) {
let map = that.mapData.map
if (map.getLayerById(attr.id + 'box')) {
map.getLayerById(attr.id + 'box').remove()
}
},
mapGetCameraView(that) {
let map = that.mapData.map
const camera = map.getCameraView()
alert(JSON.stringify(camera), '当前视角参数')
},
//绘制面
startDrawGraphic(that) {
const mars3d = that.mars3d
let map = that.mapData.map
let graphicLayer = new mars3d.layer.GraphicLayer({ id: 'startDrawGraphic' })
map.addLayer(graphicLayer)
map.on(mars3d.EventType.rightClick, (event) => {
bindLayerContextMenu()
})
graphicLayer.startDraw({
type: 'polygon',
style: {
color: '#29cf34',
opacity: 0.5,
outline: true,
outlineWidth: 3,
outlineColor: '#ffffff',
label: {
text: '',
font_size: 18,
color: '#fff',
distanceDisplayCondition: true,
distanceDisplayCondition_far: 500000,
distanceDisplayCondition_near: 0
}
}
})
function bindLayerContextMenu() {
graphicLayer.bindContextMenu([
{
text: '开始编辑对象',
icon: 'fa fa-edit',
show: function (e) {
const graphic = e.graphic
if (!graphic || !graphic.hasEdit) {
return false
}
return !graphic.isEditing
},
callback: (e) => {
const graphic = e.graphic
if (!graphic) {
return false
}
if (graphic) {
graphicLayer.startEditing(graphic)
}
}
},
{
text: '停止编辑对象',
icon: 'fa fa-edit',
show: function (e) {
const graphic = e.graphic
if (!graphic || !graphic.hasEdit) {
return false
}
return graphic.isEditing
},
callback: (e) => {
const graphic = e.graphic
if (!graphic) {
return false
}
if (graphic) {
graphic.stopEditing()
}
}
},
{
text: '删除对象',
icon: 'fa fa-trash-o',
show: (event) => {
const graphic = event.graphic
if (!graphic || graphic.isDestroy) {
return false
} else {
return true
}
},
callback: (e) => {
const graphic = e.graphic
if (!graphic) {
return
}
const parent = graphic.parent // 右击是编辑点时
graphicLayer.removeGraphic(graphic)
if (parent) {
graphicLayer.removeGraphic(parent)
}
}
}
])
}
},
/**
* 初始化外台军力量地图图层
* @param {*} that 获取当前地图实例
*/
initEnemyLayer({ mars3d, mapData }) {
let map = mapData.map
//创建标注点位图层实列
graphicEnemyMarkerGate = new mars3d.layer.GraphicLayer({
allowDrillPick: true, // 如果存在坐标完全相同的图标点,可以打开该属性,click事件通过graphics判断
})
map.addLayer(graphicEnemyMarkerGate)
},
/**
* 绘制外台军力量地图标注
* @param {*} that 地图实例 传入this
* @param {*} options 位置数据
*/
addDrawEnemyMark(that, { lng, lat, connectionStatus }) {
const mars3d = that.mars3d
console.log("开始绘制外台军力量地图标注")
// 创建图标标注
let markerGate = new mars3d.graphic.BillboardEntity({
position: [lng, lat, 1000], // 坐标点位和高度值
attr: { 'name': 'EnemyMark' },
style: {
image: 'img/marker/mark-blue.png', // 自定义点位展示图标
scale: 1,
horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
label: 'EnemyMark'
}
})
// 添加标注
graphicEnemyMarkerGate.addGraphic(markerGate)
// 创建提示框(联通状态)标签
let labelEntity = new mars3d.graphic.LabelEntity({
position: new mars3d.LngLatPoint(lng, lat, 1000), // 与标注相同的坐标
style: {
text: connectionStatus === '正常' ? '联通正常' : '联通异常', // 根据状态显示文字
font_size: 46,
scale: 0.5, // scale传0.5
font_family: "楷体",
color: connectionStatus === '正常' ? '#00FF00' : '#FF0000', // 正常为绿色,异常为红色
hasPixelOffset:true,
horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
background: true, // 添加背景框
backgroundColor: connectionStatus === '正常' ? 'rgba(0, 255, 0, 0.5)' : 'rgba(255, 0, 0, 0.5)', // 背景色根据状态变化
backgroundPadding: new Cesium.Cartesian2(10, 6), // 背景框内边距
pixelOffsetY:-40,
outlineColor: "#000000",
outlineWidth: 2,
visibleDepth: false
},
attr: {
remark: "示例1" ,
name:'EnemyMark'
}
})
// 添加标签
graphicEnemyMarkerGate.addGraphic(labelEntity)
console.log('结束绘制外台军力量地图标注')
},
/**
* 设置相机俯瞰国家时的默认视角
* @param {*} this
* @param {*} options
*/
setCountryCameraView({ mapData }, { lat, lng, alt }) {
let map = mapData.map
map.setCameraView(
{ "lat": lat, "lng": lng, "alt": alt || 100000, "heading": 0, "pitch": -90 })
console.log("设置相机视角")
},
/**
* 移除外台军力量点位
*/
removeEnemyMark() {
if (!graphicEnemyMarkerGate) return
let diansgraphic = graphicEnemyMarkerGate.getGraphicsByAttr('EnemyMark', 'name')
diansgraphic.map(item => {
graphicEnemyMarkerGate.remove(item)
})
console.log('remove标注')
},
/**
* 添加战区
* @param {*} that
* @param {*} name
* @returns
*/
removeEnemyLayer(that) {
if (!graphicEnemyMarkerGate) return
let map = that.mapData.map
map.removeLayer(graphicEnemyMarkerGate)
console.log('removeLayer')
},
/**
* 添加战区
* @param {*} that
* @param {*} name
* @returns
*/
addProvinceData(that, name) {
console.log('添加战区')
let map = that.mapData.map
const mars3d = that.mars3d
let provincedata = require('@/assets/resources/geoJson/province.js')
let singleProvince = provincedata.filter(item => {
return item.name == name
})
if (singleProvince.length == 0) {
return
}
singleProvince = singleProvince[0]
graphicProvinceLayer = new mars3d.layer.GeoJsonLayer({
data: singleProvince.data,
symbol: {
styleOptions: {
type: "polygon",
color: '#ff0000',
materialType: mars3d.MaterialType.PolyGradient, // 重要参数,指定材质
materialOptions: {
color: "#ff0000",
opacity: 0.5,
alphaPower: 1.3
},
},
},
flyTo: true,
flyToOptions: {
height: 5000000
},
name: '战区'
})
map.addLayer(graphicProvinceLayer);
console.log("绘制结束")
},
/**
*
* @param {*} that
*/
removeProvinceMark(that) {
if (!graphicProvinceLayer&&!graphicAirForceLayer) return
let map = that.mapData.map
map.getLayersByAttr('战区', 'name').map(item => {
map.removeLayer(item)
})
map.getLayersByAttr('空军', 'name').map(item => {
map.removeLayer(item)
})
console.log('remove战区')
},
/**
*
* @param {*} that
*/
initAirorceArea(that) {
const mars3d = that.mars3d
const map = that.mapData.map
// 在图层绑定Popup弹窗
graphicAirForceLayer = new mars3d.layer.GraphicLayer({
name:'空军'
})
map.addLayer(graphicAirForceLayer)
graphicAirForceLayer.bindPopup(function (event) {
const attr = event.graphic.attr || {}
return mars3d.Util.getTemplateHtml({ title: "空军", template: "all", attr })
})
},
drawAirorceArea(that, { data }) {
const mars3d = that.mars3d
const graphic = new mars3d.graphic.PolygonEntity({
positions: [
data
],
style: {
color: "#ff0000",
opacity: 0.4,
outline: true,
materialType: mars3d.MaterialType.PolyGradient, // 重要参数,指定材质
materialOptions: {
color: "#ff0000",
opacity: 0.5,
alphaPower: 1.3
},
},
height: 100000,
name: "责任区",
attr: { "类型": "示例责任区" }
})
graphicAirForceLayer.addGraphic(graphic) // 还可以另外一种写法: graphic.addTo(graphicLayer)
},
drawAirSpace(that, data ) {
console.log("绘制空域")
const mars3d = that.mars3d
const graphic = new mars3d.graphic.RectangleEntity({
positions: data.data
,
style: {
color: "#ffffff",
opacity: 0.4,
outline: true,
},
name: "空域",
attr: { "空域编号": data.id,"所属单位":data.department,"是否在用":data.isUse}
})
graphicAirForceLayer.addGraphic(graphic)
},
drawAirLine(that,data) {
const mars3d = that.mars3d
const startPoint = Cesium.Cartesian3.fromDegrees(data.startPoint[0],data.startPoint[1])
const endPoint = Cesium.Cartesian3.fromDegrees(data.endPoint[0], data.endPoint[1])
const positions = mars3d.PolyUtil.getLinkedPointList(startPoint, endPoint, 20000, 1000) // 计算曲线点
const graphic = new mars3d.graphic.PolylineEntity({
positions,
style: {
width: 4,
materialType: mars3d.MaterialType.LineFlowColor,
materialOptions: {
image: "img/marker/mark-blue.png",
color: "#ff0000",
speed: 20,
percent: 0.2,
alpha: 0.5
}
},
attr: { "航线": "示例航线" },
name: "航线"
})
graphicAirForceLayer.addGraphic(graphic)
},
removeAirforceArea() {
if (!graphicAirForceLayer) return
if (graphicAirForceLayer.isDestroy) return
let diansgraphic = graphicAirForceLayer.getGraphicsByAttr('责任区', 'name')
diansgraphic.map(item => {
graphicAirForceLayer.remove(item)
})
console.log('remove责任区')
},
removeAirSpace() {
if (!graphicAirForceLayer) return
if (graphicAirForceLayer.isDestroy) return
let diansgraphic = graphicAirForceLayer.getGraphicsByAttr('空域', 'name')
diansgraphic.map(item => {
graphicAirForceLayer.remove(item)
})
console.log('remove空域')
},
removeAireLine() {
if (!graphicAirForceLayer) return
if (graphicAirForceLayer.isDestroy) return
let diansgraphic = graphicAirForceLayer.getGraphicsByAttr('航线', 'name')
diansgraphic.map(item => {
graphicAirForceLayer.remove(item)
})
console.log('remove航')
},
removeAirforceLayer(that) {
const map = that.mapData.map
if (graphicAirForceLayer) {
map.removeLayer(graphicAirForceLayer)
graphicAirForceLayer = null
}
},
// 直接绘制点 (不是自己画 是直接根据经纬度绘制)
initDrawCurrentPoint(that, position, prevId) {
const mars3d = that.mars3d
let map = that.mapData.map
if (map.getLayerById('CurrentPoint' + prevId)) {
map.getLayerById('CurrentPoint' + prevId).remove()
}
if (map.getLayerById('Sector' + prevId)) {
map.getLayerById('Sector' + prevId).remove()
}
let graphicLayer = new mars3d.layer.GraphicLayer({ id: 'CurrentPoint' + position.id })
map.addLayer(graphicLayer)
const graphic = new mars3d.graphic.BillboardEntity({
viewFrom: new Cesium.Cartesian3(-500, -500, 200),
id: 'CurrentPoint' + position.id,
// position: new mars3d.LngLatPoint(position.lng, position.lat, position.alt),
position: [position.lng, position.lat, position.alt],
style: {
image: 'img/marker/point-red.png',
scale: 1,
horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
scaleByDistance: new Cesium.NearFarScalar(10000, 1.0, 100000, 0.1)
},
})
graphicLayer.addGraphic(graphic) // 还可以另外一种写法: graphic.addTo(graphicLayer)
graphic.bindPopup(
`<div style='width: 200px'>
<div>经 度:<span id='lblAllLen'>${position.lng}</span></div>
<div>维 度:<span id='lblAllLen'>${position.lat}</span></div>
<div>高 度:<span id='lblAllLen'>${position.alt}</span></div>
<div>航 速:<span id='lblAllLen'>${position.fs}</span></div>
<div>航 向:<span id='lblAllLen'>${position.fx}</span></div>
<div>风 速:<span id='lblAllLen'>${position.hs}</span></div>
<div>风 向:<span id='lblAllLen'>${position.hx}</span></div>
</div>`,
{
// 设置偏移量,向上偏移10像素
offsetY: -30,
closeOnClick: false
}
).openPopup()
},
initDrawPrevPoint(that, prevPosition,prevId) {
const mars3d = that.mars3d
let map = that.mapData.map
let graphicLayer = new mars3d.layer.GraphicLayer({ id: 'PrevPoint' + prevPosition.id })
map.addLayer(graphicLayer)
const graphic = new mars3d.graphic.PointEntity({
position: [prevPosition.lng, prevPosition.lat, prevPosition.alt],
style: {
color: '#bc1b1b',
pixelSize: 10,
outline: true,
outlineColor: '#ffffff',
outlineWidth: 2
},
})
graphicLayer.addGraphic(graphic)
},
addRoamLines(that, position, prevPosition,prevId) {
const mars3d = that.mars3d
let map = that.mapData.map
map.clock.multiplier = 10
let graphicLayer = new mars3d.layer.GraphicLayer({ id: 'Line' + position.id })
map.addLayer(graphicLayer)
const arrLine = [
{
name: '空飘物',
speed: 500,
positions: [
[prevPosition.lng, prevPosition.lat, prevPosition.alt],
[position.lng, position.lat, position.alt]
],
// model: {
// url: "img/marker/point-red.png",
// scale: 0.01,
// minimumPixelSize: 60
// },
style: {
// image: 'img/marker/point-red.png',
scale: 1,
horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
scaleByDistance: new Cesium.NearFarScalar(10000, 1.0, 100000, 0.1)
},
path: {
color: '#ffff00',
width: 3,
leadTime: 0
}
}
]
let startTime
let stopTime
const flydata = arrLine[0]
flydata.updateClock = false // 多个FixedRoute模型,避免时钟冲突
flydata.label = {
text: flydata.name,
font_size: 20,
pixelOffsetX: 0,
pixelOffsetY: -20,
scaleByDistance: false,
scaleByDistance_far: 80000,
scaleByDistance_farValue: 0.4,
distanceDisplayCondition: true,
distanceDisplayCondition_far: 80000
}
flydata.billboard = {
...flydata.style
}
const fixedRoute = new mars3d.graphic.FixedRoute(flydata)
graphicLayer.addGraphic(fixedRoute)
// 启动漫游
fixedRoute.start()
startTime = fixedRoute.startTime
stopTime = fixedRoute.stopTime
},
// 绘制方向角 预测 开始角度(正东方向为0,顺时针到360度)
initDrawPointSector(that, position) {
const mars3d = that.mars3d
let map = that.mapData.map
let graphicLayer = new mars3d.layer.GraphicLayer({ id: 'Sector' + position.id })
map.addLayer(graphicLayer)
const graphic = new mars3d.graphic.Sector({
// 108.839171049151, 35.035885988431
id: 'Sector' + position.id,
positions: [
[position.lng, position.lat, position.alt]
],
style: {
radius: 300,
startAngle: position.startAngle, // 开始角度(正东方向为0,顺时针到360度)
endAngle: position.endAngle,
color: '#bc1b1b',
opacity: 0.5,
outline: true,
outlineWidth: 3,
outlineColor: '#0a34f8'
},
attr: { remark: '示例1' }
})
graphicLayer.addGraphic(graphic) // 还可以另外一种写法: graphic.addTo(graphicLayer)
},
// 绘制线
initDrawLine(that, position, prevPosition) {
const mars3d = that.mars3d
let map = that.mapData.map
let graphicLayer = new mars3d.layer.GraphicLayer({ id: 'Line' + position.id })
map.addLayer(graphicLayer)
const graphic = new mars3d.graphic.PolylinePrimitive({
positions: [
[position.lng, position.lat, position.alt],
[prevPosition.lng, prevPosition.lat, prevPosition.alt]
],
style: {
width: 3,
color: '#0a34f8'
},
attr: { remark: '示例5' }
})
graphicLayer.addGraphic(graphic)
},
// 阵地--图层打点
addGraphicPointZD(that, data) {
const mars3d = that.mars3d
let map = that.mapData.map
let Cesium = that.Cesium
if (map.getLayerById('pointLayerZD')) {
map.getLayerById('pointLayerZD').remove()
}
// console.log('dataaaaaa',data);
map.setCameraView({ 'lng': data.jd, 'lat': data.wd, 'alt': 220000, 'heading': 0, 'pitch': -90 })
//创建标注点位图层实列
graphicLayerZD = new mars3d.layer.GraphicLayer({
id: 'pointLayerZD',
allowDrillPick: true // 如果存在坐标完全相同的图标点,可以打开该属性,click事件通过graphics判断
})
map.addLayer(graphicLayerZD)
// for (let i = 0, len = points.length; i < len; i++) {
const item = data
let markerGate = new mars3d.graphic.BillboardEntity({
position: [item.jd, item.wd, 1000],//坐标点位和高度值
style: {
image: 'img/marker/hq.png',
scale: 1,
horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
clampToGround: true, //贴地
},
name: '阵地标记点',
attr: {
'标记点': item.zdmc,
}
})
graphicLayerZD.addGraphic(markerGate)
// 绑定popup
const innerHtml = `<table style="width:280px;">
<tr><th scope="col" colspan="4" style="text-align:left;font-size:16px;padding-bottom: 10px;">${item.zdmc}</th></tr>
<tr><td style="width:100px;">经度:</td><td >${item.jd}</td></tr>
<tr><td style="width:100px;">纬度:</td><td >${item.wd}</td></tr>
<tr><td style="width:100px;">海拔高度:</td><td >${item.hbgd}</td></tr>
<tr><td style="width:100px;">武器型号:</td><td >${item.bqsy}</td></tr>
<tr><td style="width:100px;">遮蔽物情况:</td><td >${item.zbwqk}</td></tr>
<tr><td style="width:100px;">道路桥梁情况:</td><td >${item.dlqlqk}</td></tr>
<tr><td style="width:100px;">阵地土质情况:</td><td >${item.dztjjbzxq}</td></tr>
</table>`
markerGate.bindPopup(innerHtml, { offsetY: -10, closeOnClick: true })
// }
},
removeGraphicPointZD(that) {
console.log(graphicLayerZD)
if (!graphicLayerZD) return
if(graphicLayerZD._state =='destroy')return
// let map = that.mapData.map
let diansgraphic = graphicLayerZD.getGraphicsByAttr('阵地标记点', 'name')
diansgraphic.map(item => {
graphicLayerZD.remove(item)
})
// map.removeLayer(graphicLayerZD)
console.log('remove阵地')
},
}
// 地图测量工具
class mapUtilMeasure {
mapObj = null
measure = ''
// 初始化测量工具对象
constructor(that) {
this.mapObj = that
if (that.mapData.map.getLayerById('measure')) {
that.mapData.map.getLayerById('measure').remove()
}
that.mars3d.DrawUtil.setAllEditPointStyle({ pixelSize: 14 })
let measure = new that.mars3d.thing.Measure({
label: {
color: '#ffffff',
font_family: '楷体',
font_size: 20,
background: false
},
id: 'measure'
})
this.measure = measure
that.mapData.map.addThing(measure)
that.mapData.layers.push(measure)
measure.on(that.mars3d.EventType.start, function (e) {
console.log('开始异步分析', e)
})
measure.on(that.mars3d.EventType.end, function (e) {
console.log('完成异步分析', e)
})
}
// 空间距离
measureLength() {
this.measure.distance({
showAddText: true,
label: {
// type: 'div',
color: '#ffffff',
font_family: '楷体',
font_size: 30,
background: false
// updateText: function (text, graphic) {
// graphic.html = `<div class='marsGreenGradientPnl' >${text}</div>`
// },
// html: `<div class='marsGreenGradientPnl' ></div>`,
// horizontalOrigin: this.mapObj.Cesium.HorizontalOrigin.CENTER,
// verticalOrigin: this.mapObj.Cesium.VerticalOrigin.BOTTOM
}
})
}
// 贴地距离
measureSurfaceLength() {
this.measure.distanceSurface({
showAddText: true,
exact: false,
label: {
color: '#ffffff',
font_family: '楷体',
font_size: 30,
background: false
}
})
}
// 水平面积
measureArea() {
this.measure.area({
label: {
color: '#ffffff',
font_family: '楷体',
font_size: 30,
background: false
},
})
}
// 贴地面积
measureSurfaceeArea() {
this.measure.areaSurface({
style: {
color: '#ffff00',
},
label: {
color: '#ffffff',
font_family: '楷体',
font_size: 30,
background: false
},
splitNum: 10, // step插值分割的个数
exact: false // 是否进行精确计算, 传false时是否快速概略计算方式,该方式计算精度较低,但计算速度快,仅能计算在当前视域内坐标的高度
})
}
// 高度差
measureHeight() {
this.measure.height({
label: {
color: '#ffffff',
font_family: '楷体',
font_size: 30,
background: false
},
})
}
// 三角测量
measureTriangleHeight() {
this.measure.heightTriangle({
label: {
color: '#ffffff',
font_family: '楷体',
font_size: 30,
background: false
},
})
}
// 方位角
measureAngle() {
this.measure.angle({
label: {
color: '#ffffff',
font_family: '楷体',
font_size: 30,
background: false
},
})
}
// 坐标测量
measurePoint() {
this.measure.point({
// popup: function (point, graphic) {
// return `<div class="mars3d-template-title">位置信息</div>
// <div class="mars3d-template-content">
// <div><label>经度</label>${point.lng}</div>
// <div><label>纬度</label>${point.lat}</div>
// <div><label>海拔</label>${point.alt}米</div>
// </div>`
// }
})
}
// 打开json
openJSON(file) {
const fileName = file.name
const fileType = fileName?.substring(fileName.lastIndexOf('.') + 1, fileName.length).toLowerCase()
if (fileType === 'json') {
let that = this
const reader = new FileReader()
reader.readAsText(file, 'UTF-8')
reader.onloadend = function () {
const geojson = JSON.parse(this.result)
if (geojson.type === 'graphic' && geojson.data) {
that.measure.graphicLayer.addGraphic(geojson.data)
that.measure.graphicLayer.flyTo()
} else {
that.measure.graphicLayer.loadGeoJSON(geojson, { flyTo: true })
}
}
} else {
console.log('暂不支持 ' + fileType + ' 文件类型的数据!')
}
}
// 保存json
saveJSON() {
if (this.measure.graphicLayer.length === 0) {
console.log('当前没有标注任何数据,无需保存!')
return
}
const geojson = this.measure.graphicLayer.toJSON()
this.mapObj.mars3d.Util.downloadFile('测量结果.json', JSON.stringify(geojson))
}
// 清除
removeAll() {
this.measure.clear()
if (this.mapObj.mapData.map.getLayerById('measure')) {
this.mapObj.mapData.map.getLayerById('measure').remove()
}
}
}
export { mapUtil, mapUtilMeasure }
map.js
import Vue from 'vue'
import moment from 'moment'
import * as turf from '@turf/turf'
import { Cesium } from 'mars3d'
let mapUtilMapDraw = {
// 网格
squareGrid(that, data, centerJD, centerWD, flag) {
let map = that.mapData.map
map.setCameraView({ lat: centerWD, lng: centerJD, alt: 2639009.2, heading: 353.2, pitch: -86.1 })
let jl = flag * 1 > 2 ? 150000 : 889824
drawFjPoint(data)
function drawFjPoint(data) {
// 蜂窝网格、正方形网格、三角形网格
const mars3d = that.mars3d
let graphicLayer = new mars3d.layer.GraphicLayer({ id: 'startDrawGrid' })
graphicLayer.clear()
map.addLayer(graphicLayer)
that.mapData.layers.push(graphicLayer)
for (let i = 0; i < data.length; i++) {
const item = data[i]
let name = item.wgbm
const graphic = new mars3d.graphic.PolygonEntity({
positions: [[item.jd3, item.wd3], [item.jd1, item.wd1], [item.jd2, item.wd2], [item.jd4, item.wd4]],
style: {
color: '#fff',
opacity: 0.1,
outline: true,
outlineWidth: 1,
outlineColor: '#fff',
outlineOpacity: 0.5,
clampToGround: true,
label: {
text: name ? name : ' ',
distanceDisplayCondition: true,
distanceDisplayCondition_far: jl,
color: '#ff0'
}
},
attr: item.attr,
popup: name ? name : ' '
})
graphicLayer.addGraphic(graphic)
}
}
},
// 清除网格
clearSquareGrid(that) {
let map = that.mapData.map
if (map.getLayerById('startDrawGrid')) {
map.getLayerById('startDrawGrid').remove()
}
},
//旧版计划网格
squareOldGrid(that, data, attr) {
let map = that.mapData.map
map.setCameraView({ lat: data[0][0][1], lng: data[0][0][0], alt: 1000000.2, heading: 353.2, pitch: -86.1 })
const mars3d = that.mars3d
let graphicLayer = new mars3d.layer.GraphicLayer({ id: 'startDrawGrid' })
graphicLayer.clear()
map.addLayer(graphicLayer)
that.mapData.layers.push(graphicLayer)
for (let i = 0; i < data.length; i++) {
let str = ''
for (let j = 0; j < attr[i].length; j++) {
if (attr[i][j].isflag) {
let isCT = attr[i][j].isflag === '0' ? ',时间未冲突' : ',时间有冲突'
str += attr[i][j].dbmc + '机型为:' + attr[i][j].fjJx + ',飞行员' + attr[i][j].qcxm + '起飞时间为' + attr[i][j].qfsk + ',架次编号为' + attr[i][j].jcbh + ',空中时间为' + attr[i][j].kzsj + isCT + '</br>'
}
if (attr[i][j].sfgb) {
str = attr[i][j].sfgb === '0' ? '未分配' : '已关闭'
}
}
let ctColor = ''
let opacity = 0.1
if (str.includes('未冲突')) {
ctColor = '#0f0'
opacity = 0.1
}
if (str.includes('有冲突')) {
ctColor = '#f00'
opacity = 0.1
}
if (str.includes('未分配')) {
ctColor = '#fff'
opacity = 0.1
}
if (str.includes('已关闭')) {
ctColor = '#999'
opacity = 0.3
}
const item = data[i]
str = attr[i].length === 0 ? '未计划' : str
const graphic = new mars3d.graphic.PolygonEntity({
positions: item,
style: {
color: ctColor,
opacity: 0.1,
outline: true,
outlineWidth: 1,
outlineColor: ctColor,
outlineOpacity: 0.5,
clampToGround: true,
label: {
text: attr[i].length > 0 ? (attr[i][0].kybh ? attr[i][0].kybh : '未计划') : '未计划',
distanceDisplayCondition: true,
distanceDisplayCondition_far: 889824,
color: '#ff0'
}
},
attr: attr[i],
popup: str
})
graphicLayer.addGraphic(graphic)
}
// }
},
//旧版实施网格
//标会钳击箭头
drawPolygon(that, type) {
const mars3d = that.mars3d
let map = that.mapData.map
let graphicLayer = new mars3d.layer.GraphicLayer(
{ id: 'startDrawIcon' })
map.addLayer(graphicLayer)
graphicLayer.startDraw({
type,
styleType: 'polygon',
style: {
color: '#ff0000',
opacity: 0.6,
outline: true,
outlineWidth: 3,
outlineColor: '#ff0000',
clampToGround: true
}
})
graphicLayer.bindContextMenu([
{
text: '开始编辑对象',
icon: 'fa fa-edit',
show: function(e) {
const graphic = e.graphic
if (!graphic || !graphic.hasEdit) {
return false
}
return !graphic.isEditing
},
callback: (e) => {
const graphic = e.graphic
if (!graphic) {
return false
}
if (graphic) {
graphicLayer.startEditing(graphic)
}
}
},
{
text: '更改对象颜色',
icon: 'fa fa-edit',
callback: (e) => {
// color: "#ff0000" 红 #0000ff 蓝
const graphic = e.graphic
console.log(graphic.style.color, '12312321312')
if (graphic.style.color === '#ff0000') {
graphic.setStyle({
color: '#0000ff',
outlineColor: '#0000ff',
opacity: 0.6,
outline: true,
outlineWidth: 3,
clampToGround: false
})
} else if (graphic.style.color === '#0000ff') {
graphic.setStyle({
color: '#ff0000',
outlineColor: '#ff0000',
opacity: 0.6,
outline: true,
outlineWidth: 3,
clampToGround: false
})
}
}
},
{
text: '停止编辑对象',
icon: 'fa fa-edit',
show: function(e) {
const graphic = e.graphic
if (!graphic || !graphic.hasEdit) {
return false
}
return graphic.isEditing
},
callback: (e) => {
const graphic = e.graphic
if (!graphic) {
return false
}
if (graphic) {
graphic.stopEditing()
}
}
},
{
text: '删除对象',
icon: 'fa fa-trash-o',
show: (event) => {
const graphic = event.graphic
if (!graphic || graphic.isDestroy) {
return false
} else {
return true
}
},
callback: (e) => {
const graphic = e.graphic
if (!graphic) {
return
}
const parent = graphic.parent // 右击是编辑点时
graphicLayer.removeGraphic(graphic)
if (parent) {
graphicLayer.removeGraphic(parent)
}
}
}
])
},
startDrawGraphic(that) {
const mars3d = that.mars3d
let map = that.mapData.map
let graphicLayer = new mars3d.layer.GraphicLayer(
{ id: 'startDrawGraphic' })
map.addLayer(graphicLayer)
map.on(mars3d.EventType.click, function(event) {
var cartesian = event.cartesian
var point = mars3d.LngLatPoint.fromCartesian(cartesian)
point.format() //经度、纬度、高度
console.log('---------- 当前坐标位置信息 ----------')
console.log('当前经度:' + point.lng)
console.log('当前纬度:' + point.lat)
console.log('当前高度:' + point.alt)
const graphic = new mars3d.graphic.BillboardEntity({
name: '贴地图标',
position: [point.lng, point.lat, point.alt],
style: {
image: 'img/marker/mark-blue.png',
scale: 1,
horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
clampToGround: true
},
attr: { remark: '示例3' }
})
graphicLayer.addGraphic(graphic)
})
graphicLayer.bindPopup(
function(event) {
var position = event.graphic.points[0].format()
var lat = position.lat // 纬度
var lng = position.lng // 经度
var alt = position.alt // 高度(可能是相对于ellipsoid的)
const attr = '经度: ' + lng + ', : ' + lat + ', 高度: ' + alt
return attr
// return new Promise((resolve) => {
// // 这里可以进行后端接口请求数据,setTimeout测试异步
// setTimeout(() => {
// resolve("Promise异步回调显示的弹窗内容信息")
// }, 2000)
// })
},
{ timeRender: true, closeButton: false } // timeRender实时刷新
)
graphicLayer.bindContextMenu([
{
text: '开始编辑对象',
icon: 'fa fa-edit',
show: function(e) {
const graphic = e.graphic
if (!graphic || !graphic.hasEdit) {
return false
}
return !graphic.isEditing
},
callback: (e) => {
const graphic = e.graphic
if (!graphic) {
return false
}
if (graphic) {
graphicLayer.startEditing(graphic)
}
}
},
{
text: '停止编辑对象',
icon: 'fa fa-edit',
show: function(e) {
const graphic = e.graphic
if (!graphic || !graphic.hasEdit) {
return false
}
return graphic.isEditing
},
callback: (e) => {
const graphic = e.graphic
if (!graphic) {
return false
}
if (graphic) {
graphic.stopEditing()
}
}
},
{
text: '删除对象',
icon: 'fa fa-trash-o',
show: (event) => {
const graphic = event.graphic
if (!graphic || graphic.isDestroy) {
return false
} else {
return true
}
},
callback: (e) => {
const graphic = e.graphic
if (!graphic) {
return
}
const parent = graphic.parent // 右击是编辑点时
graphicLayer.removeGraphic(graphic)
if (parent) {
graphicLayer.removeGraphic(parent)
}
}
},
{
text: '提交',
icon: 'fa fa-edit',
callback: (e) => {
// color: "#ff0000" 红 #0000ff 蓝
const graphic = e.graphic
console.log(graphic, '12312321312')
var position = graphic.points[0].format()
var lat = position.lat // 纬度
var lng = position.lng // 经度
var alt = position.alt // 高度(可能是相对于ellipsoid的)
console.log('经度: ' + lng + ', : ' + lat + ', 高度: ' + alt)
}
}
])
},
startDrawQd(that) {
const mars3d = that.mars3d
let map = that.mapData.map
if (map.getLayerById('startDrawQd')) {
map.getLayerById('startDrawQd').remove()
}
let graphicLayer = new mars3d.layer.GraphicLayer({ id: 'startDrawQd' })
map.addLayer(graphicLayer)
map.on(mars3d.EventType.click, function(event) {
var cartesian = event.cartesian
var point = mars3d.LngLatPoint.fromCartesian(cartesian)
point.format() //经度、纬度、高度
// console.log('---------- 当前坐标位置信息 ----------')
// console.log('当前经度:' + point.lng)
// console.log('当前纬度:' + point.lat)
// console.log('当前高度:' + point.alt)
that.zdxslcQd = point.lng+ "," + point.lat
console.log('---------- 起点坐标位置信息 ----------',that.zdxslcQd)
const graphic = new mars3d.graphic.BillboardEntity({
name: '贴地图标',
position: [point.lng, point.lat, point.alt],
style: {
image: 'img/marker/qd.png',
scale: 1,
horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
clampToGround: true,
highlight: {
scale: 1
}
},
})
graphicLayer.addGraphic(graphic)
})
},
startDrawZd(that) {
const mars3d = that.mars3d
let map = that.mapData.map
if (map.getLayerById('startDrawZd')) {
map.getLayerById('startDrawZd').remove()
}
let graphicLayer = new mars3d.layer.GraphicLayer({ id: 'startDrawZd' })
map.addLayer(graphicLayer)
map.on(mars3d.EventType.click, function(event) {
var cartesian = event.cartesian
var point = mars3d.LngLatPoint.fromCartesian(cartesian)
point.format() //经度、纬度、高度
console.log('---------- 当前坐标位置信息 ----------')
console.log('当前经度:' + point.lng)
console.log('当前纬度:' + point.lat)
console.log('当前高度:' + point.alt)
that.zdxslcZd = point.lng+ "," + point.lat
console.log('---------- 终点坐标位置信息 ----------',that.zdxslcZd)
const graphic = new mars3d.graphic.BillboardEntity({
name: '贴地图标',
position: [point.lng, point.lat, point.alt],
style: {
image: 'img/marker/zd.png',
scale: 1,
horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
clampToGround: true,
highlight: {
scale: 1
}
},
})
graphicLayer.addGraphic(graphic)
})
}
// 该方法演示 自定义拖拽div(定义在 DivIndicator.js 中) ,可以参考自行扩展算法
// addDemoGraphic1(graphicLayer) {
// const divIndicator = new DivIndicator({
// position: [116.115794, 30.973847, 1455.6],
// style: {
// html: ` <div class="divIndicator-fixed"></div>
// <div class="divIndicator-line"></div>
// <div class="divIndicator-drag">连线位置会随拖拽自适应最近顶点</div> `,
// offsetX: -6,
// offsetY: 6
// },
// attr: { remark: "示例1" }
// })
// graphicLayer.addGraphic(divIndicator)
//
// }
}
export { mapUtilMapDraw }