cesium绘制区域

<template>
<div id=”cesiumContainer”>
<div id=”cesiumDiv”>
<div id=”tools”>

<el-button @click=”polyBtn”>绘制区域</el-button>

<el-button @click=”clearBtn”>清除</el-button>
</div>
</div>
</div>
</template>
<script>
import * as Cesium from “cesium/Cesium”;
import “cesium/Widgets/widgets.css”;
import CesiumViewer from ‘./CesiumViewer.vue’
Cesium.Ion.defaultAccessToken =
“eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI3NWUyODk3ZS1iYWNjLTQ0ZjUtOTZmMC01Yzg3OTMyY2MxNzEiLCJpZCI6Nzc3OCwic2NvcGVzIjpbImFzbCIsImFzciIsImFzdyIsImdjIl0sImlhdCI6MTU1NzIxNDAwNH0.4W7rIZnGnVtW9rzUbNLfUZCo7mWRpfwVqZdTIZ4I9po”;
export default {
name: “cesiumhuizhi”,
components:{CesiumViewer},
props: {
opacity: {
type: Number,
default: 0.3,
},
factor: {
type: String,
default: “CO”,
},
},
watch: {
factor: {
handler(newV, oldV) {
if (newV !== oldV) {
if (this.timer) clearInterval(this.timer);
this.index = 0;
}
},
},
opacity: {
handler(newV, oldV) {
if (newV !== oldV) {
const polygon = this.viewer.entities.getById(“polygon”);
if (polygon) this.viewer.entities.remove(polygon);
this.addimgd();
}
},
},
},
data() {
return {
timer: null,
viewer: {},
index: 0,
// imgurl:’cnc_NO_gas_’,
urls: [],
path: “../../static/air/20210301”,
play: {},
removeImageryLayers:[]
};
},
computed: {
imgurl() {
if (this.factor === “PM2.5”) {
return “cnc_PM2_5_gas_”;
} else {
return “cnc_” + this.factor + “_gas_”;
}
},
},
methods: {
getImageryProviderArrForOnline() {
var e,
r = [];
return (
(e = new Cesium.ProviderViewModel({
name: “天地影像底图”,
tooltip: “天地图全球影像地图服务(国家基础地理信息中心)”,
iconUrl: require(“../assets/tdt_img.png”),
creationFunction: function () {
return new Cesium.WebMapTileServiceImageryProvider({
url:
“http://t7.tianditu.gov.cn/img_w/wmts?tk=51bc8c520a44e2127c07633167b28aa8”,
layer: “img”,
style: “default”,
tileMatrixSetID: “w”,
format: “tiles”,
subdomains: [“t0”, “t1”, “t2”, “t3”, “t4”, “t5”, “t6”, “t7”],
show: false,
maximumLevel: 18,
});
},
})),
r.push(e),
(e = new Cesium.ProviderViewModel({
name: “天地矢量底图”,
tooltip: “天地图全球矢量地图服务(国家基础地理信息中心)”,
iconUrl: require(“../assets/tdt_vec.png”),
creationFunction: function () {
return new Cesium.WebMapTileServiceImageryProvider({
url:
“http://t7.tianditu.gov.cn/vec_w/wmts?tk=51bc8c520a44e2127c07633167b28aa8”,
layer: “vec”,
style: “default”,
tileMatrixSetID: “w”,
format: “tiles”,
subdomains: [“t0”, “t1”, “t2”, “t3”, “t4”, “t5”, “t6”, “t7”],
show: false,
maximumLevel: 18,
});
},
})),
r.push(e),
(e = new Cesium.ProviderViewModel({
name: “天地地形底图”,
tooltip: “天地图全球地形地图服务(国家基础地理信息中心)”,
iconUrl: require(“../assets/stamenWatercolor.png”),
creationFunction: function () {
return new Cesium.WebMapTileServiceImageryProvider({
url:
“http://t7.tianditu.gov.cn/ter_w/wmts?tk=51bc8c520a44e2127c07633167b28aa8”,
layer: “ter”,
style: “default”,
tileMatrixSetID: “w”,
format: “tiles”,
subdomains: [“t0”, “t1”, “t2”, “t3”, “t4”, “t5”, “t6”, “t7”],
show: false,
maximumLevel: 18,
});
},
})),
r.push(e),
r
);
},
getTerrainProviderViewModelsArrForOnline() {
return [
new Cesium.ProviderViewModel({
name: “无地形”,
tooltip: “WGS84标准球体”,
iconUrl: require(“../assets/TerrainEllipsoid.png”),
creationFunction: function () {
return new Cesium.EllipsoidTerrainProvider({
ellipsoid: Cesium.Ellipsoid.WGS84,
});
},
}),
new Cesium.ProviderViewModel({
name: “本地地形”,
tooltip: “由 本地服务 提供的高分辨率三维地形”,
iconUrl: require(“../assets/TerrainSTK.png”),
creationFunction: function () {
return new Cesium.CesiumTerrainProvider({
url: “http://192.168.0.107:8080/gxry-tms/dem_w”,
requestWaterMask: true, // required for water effects
requestVertexNormals: true, // required for terrain lighting
});
},
}),
new Cesium.ProviderViewModel({
name: “全球地形”,
tooltip: “由 Cesium官方 提供的高分辨率全球地形”,
iconUrl: require(“../assets/TerrainSTK.png”),
creationFunction: function () {
return new Cesium.createWorldTerrain({
requestWaterMask: true, // required for water effects
requestVertexNormals: true, // required for terrain lighting
});
},
}),
];
},
initCesium() {
this.viewer = new Cesium.Viewer(“cesiumContainer”, {
// sceneMode: Cesium.SceneMode.COLUMBUS_VIEW, //初始场景模式 为二维
selectionIndicator: true, //选中元素显示,默认true
animation: false, //动画控制,默认true
baseLayerPicker: true, //地图切换控件(底图以及地形图)是否显示,默认显示true
geocoder: false, //地名查找,默认true
timeline: false, //时间线,默认true
sceneModePicker: true, //2D、2.5D、3D场景切换,默认ture
navigationHelpButton: true, //操作指南,默认true
infoBox: true, //点击要素之后显示的信息,默认true
fullscreenButton: false, //全屏按钮,默认显示true
showRenderLoopErrors: false, //如果设为true,将在一个HTML面板中显示错误信息
imageryProviderViewModels: this.getImageryProviderArrForOnline(), //设置影像图列表
terrainProviderViewModels: this.getTerrainProviderViewModelsArrForOnline(), //设置地形图列表
});

window.cesiumViewer = this.viewer; //不要把cesium实例挂载到vue的data对象中(有性能问题)
},
addDom() {
window.cesiumViewer.imageryLayers.addImageryProvider(
new Cesium.WebMapTileServiceImageryProvider({
url:
“http://t7.tianditu.gov.cn/cia_w/wmts?tk=10e4a33383d86f868e6c5748e8f6cbb5”,
layer: “cia”,
style: “default”,
tileMatrixSetID: “w”,
format: “tiles”,
subdomains: [“t0”, “t1”, “t2”, “t3”, “t4”, “t5”, “t6”, “t7”],
maximumLevel: 18,
})
);
//HomeButton默认位置
window.cesiumViewer.homeButton.viewModel.command.beforeExecute.addEventListener(
function (e) {
e.cancel = true;
window.cesiumViewer.camera.flyTo({
destination: Cesium.Cartesian3.fromDegrees(
108.212861,
22.647982,
1000000
),
orientation: {
// heading: Cesium.Math.toRadians(-5.0), // 方向
// pitch: Cesium.Math.toRadians(-30.0), // 倾斜角度
// roll: 0,
},
});
}
);
},
addNav() {
window.cesiumViewer.cesiumWidget.creditContainer.style.display = “none”;
window.cesiumViewer.camera.flyTo({
destination: Cesium.Cartesian3.fromDegrees(
108.212861,
22.647982,
1000000
),
orientation: {
// heading: Cesium.Math.toRadians(-5.0), // 方向
// pitch: Cesium.Math.toRadians(-30.0), // 倾斜角度
roll: 0,
},
});
},
addimgd() {
this.viewer.camera.setView({
destination: Cesium.Rectangle.fromDegrees(89.5, 20.4, 110.4, 61.2),
});
let positions = [
Cesium.Cartesian3.fromDegrees(103.375, 17.875),
Cesium.Cartesian3.fromDegrees(113.375, 17.875),
Cesium.Cartesian3.fromDegrees(113.375, 27.875),
Cesium.Cartesian3.fromDegrees(103.375, 27.875),
];
const that = this;
this.play = {
id: “polygon”,
polygon: {
hierarchy: new Cesium.PolygonHierarchy(positions),
heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
material: new Cesium.ImageMaterialProperty({
image: new Cesium.CallbackProperty(function () {
return that.path + “/” + that.imgurl + that.index + “.png”;
}, false),
color: Cesium.Color.WHITE.withAlpha(this.opacity),
}),
},
};
this.viewer.entities.add(this.play);

const handler = new Cesium.ScreenSpaceEventHandler(
this.viewer.scene.canvas
);
handler.setInputAction(function (click) {
const position = that.viewer.scene.pickPosition(click.position);
// 将迪卡尔坐标转化为经纬度坐标
const cartographic = Cesium.Cartographic.fromCartesian(position);
// 获取经度
const lon = Cesium.Math.toDegrees(cartographic.longitude);
// 获取维度
const lat = Cesium.Math.toDegrees(cartographic.latitude);
console.log(“经度:” + lon + ” 纬度:” + lat);
// infobox
const polygon = that.viewer.entities.getById(“polygon”);
polygon.description = `<div style=”line-height:35px;”>
<div>经度 | ${lon}</div>
<div>纬度 | ${lat}</div>
</div>`;
that.$emit(“update-line”, {
longitude_x: lon,
latitude_y: lat,
});
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
},
settime(data) {
if (this.timer) clearInterval(this.timer);
if (data) {
this.timer = setInterval(() => {
this.index++;
if (this.index == 95) {
this.index = 0;
}
}, 100);
}
},
// 加载区域边界
setBorderLine() {
const promise = Cesium.GeoJsonDataSource.load(
“/static/geojson/mian.geojson”,
{
stroke: Cesium.Color.YELLOW.withAlpha(0.6),
strokeWidth: 3,
}
);
promise.then((res) => {
this.viewer.dataSources.add(res);
const entities = res.entities.values;
for (var o = 0; o < entities.length; o++) {
var r = entities[o];
r.nameID = o; //给每条线添加一个编号,方便之后对线修改样式
}
const handler = new Cesium.ScreenSpaceEventHandler(
this.viewer.scene.canvas
);
const that = this;
handler.setInputAction(function (element) {
var pickedFeature = that.viewer.scene.pick(element.position);
if (pickedFeature) {
Hightlightline(pickedFeature.id.nameID);
}
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);

var temp = new Array();
window.Hightlightline = function (nameid) {
var exists = temp.indexOf(nameid);
if (exists <= -1) {
Highlight(nameid, true);
temp.push(nameid); // 添加线nameID到数组,
} //已经是高亮状态了 再次点击修改为原始状态
else {
Highlight(nameid, false);
temp.splice(exists, 1); //删除对应的nameID
}
};
window.Highlight = function (nameid,bool) {
for (var o = 0; o < entities.length; o++) {
var m = entities[o];
if (nameid == o) {
m.polygon.material = bool?Cesium.Color.RED:Cesium.Color.YELLOW.withAlpha(0.6);
}
}
};

});
},

setPoint() {
// 市边界
// this.viewer.dataSources.add(Cesium.GeoJsonDataSource.load(‘/static/geojson/市边界.geojson’, {
// stroke: Cesium.Color.YELLOW,
// strokeWidth: 1
// }));

// 地级市行政中心
this.viewer.dataSources
.add(
Cesium.GeoJsonDataSource.load(
“/static/geojson/地级市行政中心.geojson”
)
)
.then((res) => {
const entities = res.entities.values;
entities.forEach((element) => {
element.billboard = undefined; // 设置为空,否则会出现默认标记图标
element.point = new Cesium.PointGraphics({
color: Cesium.Color.DEEPSKYBLUE.withAlpha(0.6),
pixelSize: 10,
});
});
});

// 行政中心
this.viewer.dataSources
.add(Cesium.GeoJsonDataSource.load(“/static/geojson/行政中心.geojson”))
.then((res) => {
const entities = res.entities.values;
entities.forEach((element) => {
element.billboard = undefined;
element.point = new Cesium.PointGraphics({
color: Cesium.Color.DEEPSKYBLUE,
pixelSize: 15,
});
});
});
},
polyBtn(){
var _this = this;
_this.drawPolygon(function(positions){
var wgs84_positions = [];
for(var i=0; i<positions.length; i++){
var wgs84_point = _this.Cartesian3_to_WGS84({
x: positions[i].x,
y: positions[i].y,
z: positions[i].z
});
wgs84_positions.push(wgs84_point);
}

_this.$emit(‘getlat’,wgs84_positions);
});
},
clearBtn(){
var _this = this;
_this.clearHandle();
},

//画面
drawPolygon:function(callback){
var _this = this;
var PolygonPrimitive = (function () {
function _(positions) {
this.options = {
name: ‘多边形’,
polygon: {
hierarchy: [],
perPositionHeight: true,
material: Cesium.Color.RED.withAlpha(0.4)
}
};
this.hierarchy = new Cesium.PolygonHierarchy(positions);
this._init();
}

_.prototype._init = function () {
var _self = this;
var _update = function () {
return _self.hierarchy;
};
//实时更新polygon.hierarchy
this.options.polygon.hierarchy = new Cesium.CallbackProperty(_update, false);
_this.viewer.entities.add(this.options);
};
return _;
})();

var handler = new Cesium.ScreenSpaceEventHandler(_this.viewer.scene.canvas);
var positions = [];
var poly = undefined;

//鼠标单击画点
handler.setInputAction(function (movement) {
var cartesian = _this.viewer.scene.camera.pickEllipsoid(movement.position, _this.viewer.scene.globe.ellipsoid);
if (positions.length == 0) {
positions.push(cartesian.clone());
}
positions.push(cartesian);
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
//鼠标移动
handler.setInputAction(function (movement) {
var cartesian = _this.viewer.scene.camera.pickEllipsoid(movement.endPosition, _this.viewer.scene.globe.ellipsoid);
if (positions.length >= 2) {
if (!Cesium.defined(poly)) {
poly = new PolygonPrimitive(positions);
} else {
if(cartesian != undefined){
positions.pop();
cartesian.y += (1 + Math.random());
positions.push(cartesian);
}
}
}
}, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
//鼠标右键单击结束绘制
handler.setInputAction(function (movement) {
handler.destroy();
callback(positions);
}, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
},

//清除所有Entity和ImageryLayers
clearHandle: function () {
//移除所有实体Entity
this.viewer.entities.removeAll();
//移除cesium加载的ImageryLayer
for(var i=0; i<this.removeImageryLayers.length; i++){
this.viewer.imageryLayers.remove(this.removeImageryLayers[i]);
}
},
getPointFromWindowPoint(point){
if(this.viewer.scene.terrainProvider.constructor.name==”EllipsoidTerrainProvider”) {
return this.viewer.camera.pickEllipsoid(point,this.viewer.scene.globe.ellipsoid);
} else {
var ray=this.viewer.scene.camera.getPickRay(point);
return this.viewer.scene.globe.pick(ray,this.viewer.scene);
}
},
//笛卡尔坐标系转WGS84坐标系
Cartesian3_to_WGS84: function (point) {
var cartesian33 = new Cesium.Cartesian3(point.x, point.y, point.z);
var cartographic = Cesium.Cartographic.fromCartesian(cartesian33);
var lat = Cesium.Math.toDegrees(cartographic.latitude);
var lng = Cesium.Math.toDegrees(cartographic.longitude);
var alt = cartographic.height;
return {lat: lat, lng: lng, alt: alt};
},
//WGS84坐标系转笛卡尔坐标系
WGS84_to_Cartesian3: function (point) {
var car33 = Cesium.Cartesian3.fromDegrees(point.lng, point.lat, point.alt);
var x = car33.x;
var y = car33.y;
var z = car33.z;
return {x: x, y: y, z: z};
},

//计算两点间距离
getFlatternDistance(lat1, lng1, lat2, lng2) {
var EARTH_RADIUS = 6378137.0; //单位M
var PI = Math.PI;

function getRad(d) {
return d * PI / 180.0;
}
var f = getRad((lat1 + lat2) / 2);
var g = getRad((lat1 – lat2) / 2);
var l = getRad((lng1 – lng2) / 2);

var sg = Math.sin(g);
var sl = Math.sin(l);
var sf = Math.sin(f);

var s, c, w, r, d, h1, h2;
var a = EARTH_RADIUS;
var fl = 1 / 298.257;

sg = sg * sg;
sl = sl * sl;
sf = sf * sf;

s = sg * (1 – sl) + (1 – sf) * sl;
c = (1 – sg) * (1 – sl) + sf * sl;

w = Math.atan(Math.sqrt(s / c));
r = Math.sqrt(s * c) / w;
d = 2 * w * a;
h1 = (3 * r – 1) / 2 / c;
h2 = (3 * r + 1) / 2 / s;

return d * (1 + fl * (h1 * sf * (1 – sg) – h2 * (1 – sf) * sg));
},
},
mounted() {
this.initCesium();
this.addDom();
this.addNav();
// this.addimgd();
// this.setPoint();
// this.settime(false);
// this.setBorderLine();
},
destroyed() {
if (this.timer) clearInterval(this.timer);
},
};
</script>

<style>
#cesiumContainer {
height: 100%;
}
</style>

RIPRO主题是一个优秀的主题,极致后台体验,无插件,集成会员系统
免费资源网 » cesium绘制区域

发表评论

提供最优质的资源集合

立即查看 了解详情