离线地形数据可以放在vue项目下的public/data/sjzTerrain文件下
由于地形离线数据数量太大,在vue项目编译时会报如下错误:
ERROR in EMFILE: too many open files, open 'D:\test_project\vue_cesium_demo\public\data\sjzTerrain\.tmp\14\26787\11669.hm'
这时,我们可以把离线地形数据放在本机的iis上
然后运行项目,不会报上面的错误了
// 加载地形数据
viewer.terrainProvider = await Cesium.createWorldTerrainAsync({
url: "https://[ t0-t7 ].tianditu.gov.cn/mapservice/swdx?tk=天地图token", //"data/sjzTerrain/", //"http://192.168.1.143:8963/",// Cesium.IonResource.fromAssetId(1),
requestWaterMask: true, // 控制水的流动效果
requestVertexNormals: true, //请求地形照明数据
});
viewer.scene.globe.enableLighting = true;
new Promise(async (resolve, reject) => {
this.viewer = new Cesium.Viewer(this.$refs.cesiumContainer, {
selectionIndicator: false,
infoBox: false,
contextOptions: {
// 硬件反走样,默认值为 1
msaaLevel: 8,
requestWebgl2: true,
},
animation: false,
timeline: false, // 底部时间线
fullscreenButton: false, // 全屏
vrButton: false, // VR
sceneModePicker: false, // 选择视角的模式(球体、平铺、斜视平铺)
baseLayerPicker: false, // 图层选择器(地形影像服务)
navigationHelpButton: false, // 导航帮助(手势,鼠标)
geocoder: false, // 位置查找工具
homeButton: false, // 视角返回初始位置
});
this.viewer.scene.globe.baseColor = Cesium.Color.BLACK; // 设置地球颜色
this.viewer.cesiumWidget.creditContainer.style.display = "none"; // 去除logo
window.viewer = this.viewer;
// 加载地形数据
viewer.terrainProvider = await Cesium.createWorldTerrainAsync({
url: "https://[ t0-t7 ].tianditu.gov.cn/mapservice/swdx?tk=175171c959b6f72e789fb3c45a266d55", //"data/sjzTerrain/", //"http://192.168.1.143:8963/",// Cesium.IonResource.fromAssetId(1), //"http://192.168.1.143:8963/"
requestWaterMask: true, // 控制水的流动效果
requestVertexNormals: true, //请求地形照明数据
});
viewer.scene.globe.enableLighting = true;
resolve(viewer);
}).then(() => {
});
加载地形数据后,可以根据经纬度获取高程
const positions = [
Cesium.Cartographic.fromDegrees(
114.22268842439114,
38.134979272096594
),
Cesium.Cartographic.fromDegrees(114.5199580178976, 38.1139391070047),
];
const updatedPositions = await Cesium.sampleTerrainMostDetailed(
viewer.terrainProvider,
positions
);
console.log(`updatedPositions`, updatedPositions);
try {
const updatedPositions2 = await Cesium.sampleTerrainMostDetailed(
viewer.terrainProvider,
positions,
true
);
console.log(`updatedPositions2`, updatedPositions2);
} catch (error) {
// A tile request error occurred.
}
const updatedPositions3 = await Cesium.sampleTerrain(
viewer.terrainProvider,
10,
positions
);
console.log(`updatedPositions3`, updatedPositions3);
try {
const updatedPositions4 = await Cesium.sampleTerrain(
viewer.terrainProvider,
10,
positions,
true
);
console.log(`updatedPositions4`, updatedPositions4);
} catch (error) {
// A tile request error occurred.
}
完整代码
<template>
<div class="CesiumOutbox">
<div ref="cesiumContainer" class="cesiumContainerbox"></div>
<button @click="HomeFun" class="Btnbox">Home</button>
</div>
</template>
<script>
import "cesium/Build/Cesium/Widgets/widgets.css";
import * as Cesium from "cesium";
window.Cesium = Cesium;
export default {
name: "CesiumMap",
props: {},
data() {
return {
viewer: null,
};
},
mounted() {
this.initCesium();
},
beforeDestroy() {
if (this.viewer) {
this.viewer.destroy();
this.viewer = null;
}
},
methods: {
initCesium() {
new Promise(async (resolve, reject) => {
this.viewer = new Cesium.Viewer(this.$refs.cesiumContainer, {
selectionIndicator: false,
infoBox: false,
contextOptions: {
// 硬件反走样,默认值为 1
msaaLevel: 8,
requestWebgl2: true,
},
animation: false,
timeline: false, // 底部时间线
fullscreenButton: false, // 全屏
vrButton: false, // VR
sceneModePicker: false, // 选择视角的模式(球体、平铺、斜视平铺)
baseLayerPicker: false, // 图层选择器(地形影像服务)
navigationHelpButton: false, // 导航帮助(手势,鼠标)
geocoder: false, // 位置查找工具
homeButton: false, // 视角返回初始位置
});
this.viewer.scene.globe.baseColor = Cesium.Color.BLACK; // 设置地球颜色
this.viewer.cesiumWidget.creditContainer.style.display = "none"; // 去除logo
window.viewer = this.viewer;
// viewer.imageryLayers.addImageryProvider(
// new Cesium.UrlTemplateImageryProvider({
// url: "http://webrd01.is.autonavi.com/appmaptile?&scale=1&lang=zh_cn&style=8&x={x}&y={y}&z={z}",
// minimumLevel: 1,
// maximumLevel: 18,
// crs: "WGS84", // 使用84坐标系,默认为:GCJ02
// })
// );
/*
**
//卫片 " http://webst01.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}",
//路网" https://wprd01.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=1&style=8<ype=11"
//地名" https://wprd01.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=1&style=8<ype=4"
//地名+路网 " http://webst01.is.autonavi.com/appmaptile?style=8&x={x}&y={y}&z={z}",
//矢量切片风格 " http://webrd01.is.autonavi.com/appmaptile?&scale=1&lang=zh_cn&style=8&x={x}&y={y}&z={z}",
*/
// const imageryLayer = new Cesium.ImageryLayer(
// new Cesium.UrlTemplateImageryProvider({
// url: "http://webst01.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}",
// minimumLevel: 1,
// maximumLevel: 18,
// crs: "WGS84", // 使用84坐标系,默认为:GCJ02
// })
// );
// viewer.imageryLayers.add(imageryLayer); //添加卫片
// const imageryLayer2 = new Cesium.ImageryLayer(
// new Cesium.UrlTemplateImageryProvider({
// url: "https://wprd01.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=1&style=8<ype=11",
// minimumLevel: 1,
// maximumLevel: 18,
// crs: "WGS84", // 使用84坐标系,默认为:GCJ02
// })
// );
// viewer.imageryLayers.add(imageryLayer2); ///添加路网
// const imageryLayer3 = new Cesium.ImageryLayer(
// new Cesium.UrlTemplateImageryProvider({
// url: "https://wprd01.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=1&style=8<ype=4",
// minimumLevel: 1,
// maximumLevel: 18,
// crs: "WGS84", // 使用84坐标系,默认为:GCJ02
// })
// );
// viewer.imageryLayers.add(imageryLayer3); //添加地名
// //矢量底图
// viewer.imageryLayers.addImageryProvider(
// new Cesium.WebMapTileServiceImageryProvider({
// url: "http://t0.tianditu.com/vec_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=vec&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default.jpg&tk=d6a72a78a43a2c17294b72ab26354cd6",
// layer: "tdtImgBasicLayer",
// style: "default",
// format: "image/jpeg",
// tileMatrixSetID: "GoogleMapsCompatible",
// show: false,
// // maximumLevel: 18
// })
// );
// //中文地名注记
// viewer.imageryLayers.addImageryProvider(
// new Cesium.WebMapTileServiceImageryProvider({
// url: "http://t0.tianditu.com/cia_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=cia&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default.jpg&tk=d6a72a78a43a2c17294b72ab26354cd6",
// layer: "tdtAnnoLayer",
// style: "default",
// format: "tiles",
// tileMatrixSetID: "GoogleMapsCompatible",
// show: true,
// })
// );
// viewer.imageryLayers.addImageryProvider(
// new Cesium.WebMapTileServiceImageryProvider({
// url:
// "http://{s}.tianditu.gov.cn/cia_c/wmts?service=wmts&request=GetTile&version=1.0.0" +
// "&LAYER=cia&tileMatrixSet=c&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}" +
// "&style=default&format=tiles&tk=175171c959b6f72e789fb3c45a266d55",
// layer: "tdtCva",
// style: "default",
// format: "tiles",
// tileMatrixSetID: "c",
// subdomains: ["t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7"],
// tilingScheme: new Cesium.GeographicTilingScheme(),
// tileMatrixLabels: [
// "1",
// "2",
// "3",
// "4",
// "5",
// "6",
// "7",
// "8",
// "9",
// "10",
// "11",
// "12",
// "13",
// "14",
// "15",
// "16",
// "17",
// "18",
// "19",
// ],
// maximumLevel: 18,
// })
// );
let imgLayer = new Cesium.UrlTemplateImageryProvider({
url: "SameUrlPath/{z}/{x}/{y}.png",
layer: "imgLayer",
minimumLevel: 1,
maximumLevel:10,
});
viewer.imageryLayers.addImageryProvider(imgLayer);
// viewer.camera.setView({
// destination: Cesium.Cartesian3.fromDegrees(113, 34, 15000.0),
// orientation: {
// heading: Cesium.Math.toRadians(90.0), // east, default value is 0.0 (north)
// pitch: Cesium.Math.toRadians(-90), // default value (looking down)
// roll: 0.0, // default value
// },
// });
///
// 加载地形数据
viewer.terrainProvider = await Cesium.createWorldTerrainAsync({
url: "https://[ t0-t7 ].tianditu.gov.cn/mapservice/swdx?tk=175171c959b6f72e789fb3c45a266d55", //"data/sjzTerrain/", //"http://192.168.1.143:8963/",// Cesium.IonResource.fromAssetId(1), //"http://192.168.1.143:8963/"
requestWaterMask: true, // 控制水的流动效果
requestVertexNormals: true, //请求地形照明数据
});
viewer.scene.globe.enableLighting = true;
const positions = [
Cesium.Cartographic.fromDegrees(
114.22268842439114,
38.134979272096594
),
Cesium.Cartographic.fromDegrees(114.5199580178976, 38.1139391070047),
];
const updatedPositions = await Cesium.sampleTerrainMostDetailed(
viewer.terrainProvider,
positions
);
console.log(`updatedPositions`, updatedPositions);
try {
const updatedPositions2 = await Cesium.sampleTerrainMostDetailed(
viewer.terrainProvider,
positions,
true
);
console.log(`updatedPositions2`, updatedPositions2);
} catch (error) {
// A tile request error occurred.
}
const updatedPositions3 = await Cesium.sampleTerrain(
viewer.terrainProvider,
10,
positions
);
console.log(`updatedPositions3`, updatedPositions3);
try {
const updatedPositions4 = await Cesium.sampleTerrain(
viewer.terrainProvider,
10,
positions,
true
);
console.log(`updatedPositions4`, updatedPositions4);
} catch (error) {
// A tile request error occurred.
}
// 测试数据
// 114.22268842439114 38.134979272096594
// 114.5199580178976 38.1139391070047
// 114.24207825088216 37.91371829614106
// 114.56477609722275 37.908966850537524
/
// viewer.camera.flyTo({
// destination: Cesium.Cartesian3.fromDegrees(
// 114.517971,
// 38.054466,
// 150000.0
// ),
// orientation: {
// heading: Cesium.Math.toRadians(0.0), // east, default value is 0.0 (north)
// pitch: Cesium.Math.toRadians(-90), // default value (looking down)
// roll: 0.0, // default value
// },
// duration: 2,
// });
resolve(viewer);
}).then(() => {
/
let LogLatHeight = [];
let LogLat = [];
/
let handler = new Cesium.ScreenSpaceEventHandler(
this.viewer.scene.canvas
);
handler.setInputAction((movement) => {
let ray = this.viewer.camera.getPickRay(movement.position);
if (!ray) return null;
let position = this.viewer.scene.globe.pick(ray, this.viewer.scene);
if (position) {
console.log(`movement`, movement);
// console.log(`movement.position`, movement.position);
console.log(`position`, position);
let cartograhic =
Cesium.Ellipsoid.WGS84.cartesianToCartographic(position);
console.log(`cartograhic`, cartograhic);
let log = Cesium.Math.toDegrees(cartograhic.longitude);
let lat = Cesium.Math.toDegrees(cartograhic.latitude);
let height = cartograhic.height;
console.log(`log,lat,height`, log, lat, height);
LogLatHeight.push(log, lat, height);
console.log(`LogLatHeight`, LogLatHeight);
LogLat.push(log, lat, 0);
console.log(`LogLat`, LogLat);
}
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
// this.DrawPointFun();
// this.DrawPolylineFun();
// this.DrawPolygonFun();
// this.DrawLabelFun();
// this.DrawBillboardFun();
// // this.DrawGeoJsonFun();
// // this.DrawKMLFun();
// this.DrawCesium3DTileFun();
});
},
HomeFun() {
viewer.camera.flyHome();
},
DrawPointFun() {
const dataSource = new Cesium.CustomDataSource("myPointData");
viewer.dataSources.add(dataSource);
let PointData = {
position: Cesium.Cartesian3.fromDegrees(116.1, 34, 0),
point: {
color: Cesium.Color.RED,
outlineColor: Cesium.Color.YELLOW,
outlineWidth: 5,
pixelSize: 30,
//scaleByDistance: true,
},
};
const entity = dataSource.entities.add(PointData);
},
DrawPolylineFun() {
const dataSource = new Cesium.CustomDataSource("myPolylineData");
viewer.dataSources.add(dataSource);
const PolylineData = {
name: "Red dashed line",
polyline: {
positions: Cesium.Cartesian3.fromDegreesArrayHeights([
113, 34, 0, 116, 34, 0,
]),
width: 25,
// material: new Cesium.PolylineOutlineMaterialProperty({
// color:Cesium.Color.RED,
// outlineColor:Cesium.Color.YELLOW,
// outlineWidth:10
// }),
material: new Cesium.PolylineArrowMaterialProperty(Cesium.Color.RED),
// material: new Cesium.PolylineDashMaterialProperty({
// color: Cesium.Color.RED,
// }),
},
};
const entity = dataSource.entities.add(PolylineData);
},
DrawPolygonFun() {
const dataSource = new Cesium.CustomDataSource("myPolylineData");
viewer.dataSources.add(dataSource);
let PolygonData = {
name: "Red polygon on surface",
polygon: {
hierarchy: Cesium.Cartesian3.fromDegreesArray([
115.0, 34.0, 115.0, 34.0, 115.1, 33.9, 115.0, 33.6, 115.6, 33.5,
]),
material: Cesium.Color.RED,
},
};
const entity = dataSource.entities.add(PolygonData);
},
DrawLabelFun() {
const dataSource = new Cesium.CustomDataSource("myLabelData");
viewer.dataSources.add(dataSource);
Cesium.Label.enableRightToLeftDetection = true;
let LabelData = {
position: Cesium.Cartesian3.fromDegrees(116, 34.1522222),
label: {
text: "Philadelphia",
font: "24px Helvetica",
fillColor: Cesium.Color.SKYBLUE,
outlineColor: Cesium.Color.BLACK,
outlineWidth: 2,
style: Cesium.LabelStyle.FILL_AND_OUTLINE,
},
};
dataSource.entities.add(LabelData);
},
DrawBillboardFun() {
const dataSource = new Cesium.CustomDataSource("myBillboardData");
viewer.dataSources.add(dataSource);
let BillboardData = {
position: Cesium.Cartesian3.fromDegrees(115.5, 34.1522222),
billboard: {
image: require("@/assets/logo.png"),
show: true, // default
pixelOffset: new Cesium.Cartesian2(0, 0), // default: (0, 0)
eyeOffset: new Cesium.Cartesian3(0.0, 0.0, 0.0), // default
horizontalOrigin: Cesium.HorizontalOrigin.CENTER, // default
verticalOrigin: Cesium.VerticalOrigin.BOTTOM, // default: CENTER
scale: 2.0, // default: 1.0
color: Cesium.Color.LIME, // default: WHITE
//rotation: Cesium.Math.PI_OVER_FOUR, // default: 0.0
alignedAxis: Cesium.Cartesian3.ZERO, // default
width: 200, // default: undefined
height: 200, // default: undefined
},
label: {
text: "标牌、点",
font: "24px Helvetica",
fillColor: Cesium.Color.RED,
outlineColor: Cesium.Color.BLACK,
outlineWidth: 2,
style: Cesium.LabelStyle.FILL_AND_OUTLINE,
showBackground: true,
backgroundColor: new Cesium.Color(0.165, 0.165, 0.165, 0.8),
backgroundPadding: new Cesium.Cartesian2(7, 5),
pixelOffset: new Cesium.Cartesian2(0, 50), // default: (0, 0)
eyeOffset: new Cesium.Cartesian3(0.0, 0.0, -10.0), // default
},
point: {
color: Cesium.Color.fromCssColorString("#ff0000").withAlpha(0.6),
outlineColor: Cesium.Color.YELLOW,
outlineWidth: 5,
pixelSize: 30,
//scaleByDistance: true,
},
};
let entity = dataSource.entities.add(BillboardData);
//viewer.zoomTo(entity);
},
DrawGeoJsonFun() {
var promise = Cesium.GeoJsonDataSource.load(
require("./data/hbeiprovince.json")
);
promise.then((datasource) => {
viewer.dataSources.add(datasource);
datasource.entities.values.forEach((enetity) => {
console.log(enetity);
enetity.polygon.outlineColor = Cesium.Color.RED;
enetity.polygon.material = Cesium.Color.BLUE;
enetity.polygon.height = 1000;
enetity.polygon.extrudedHeight = 2000;
});
//viewer.zoomTo(datasource);
});
},
DrawKMLFun() {
var promise = Cesium.KmlDataSource.load("data/test.kml", {
camera: viewer.scene.camera,
canvas: viewer.scene.canvas,
});
promise.then((datasource) => {
viewer.dataSources.add(datasource);
//viewer.zoomTo(datasource);
datasource.entities.values.forEach((enetity) => {
enetity.polygon.outlineColor =
Cesium.Color.fromCssColorString("#ffADDF");
enetity.polygon.material = Cesium.Color.fromCssColorString("#67ff0F");
enetity.polygon.height = 1000;
enetity.polygon.extrudedHeight = 2000;
});
});
},
async DrawCesium3DTileFun() {
// try {
// const tileset =await Cesium.Cesium3DTileset.fromUrl("data/test3dtiles/tileset.json")// await Cesium.Cesium3DTileset.fromIonAssetId(75343);
// viewer.scene.primitives.add(tileset);
// viewer.zoomTo(tileset);
// } catch (error) {
// console.log(`Error loading tileset: ${error}`);
// }
// viewer.scene.globe.depthTestAgainstTerrain = true;
/
const tilesetOption = {
skipLevelOfDetail: true,
baseScreenSpaceError: 1024,
skipScreenSpaceErrorFactor: 16,
skipLevels: 1,
immediatelyLoadDesiredLevelOfDetail: false,
loadSiblings: false,
cullWithChildrenBounds: true,
};
const modelPromise = this.AddThreeDTiles(
"data/test3dtiles/tileset.json",
tilesetOption
); // 模型切瓦后的瓦片索引文件URL
//const modelPromise = this.AddThreeDTiles(69380); // Cesium Ion Resource
modelPromise.then((tileset) => {
console.log("tileset: ", tileset);
viewer.zoomTo(tileset);
});
},
async AddThreeDTiles(url, option) {
viewer.scene.globe.depthTestAgainstTerrain = true;
// ! 写法二:
let tileset = {};
if (typeof url == "number") {
tileset = await Cesium.Cesium3DTileset.fromIonAssetId(url, option);
} else {
tileset = await Cesium.Cesium3DTileset.fromUrl(url, option);
}
viewer.scene.primitives.add(tileset);
return tileset; // 返回模型对象
},
LoadLocalMapUrl() {
// viewer.imageryLayers.addImageryProvider(new Cesium.UrlTemplateImageryProvider({
// url: "./notes/{z}/{x}/{y}.png",
// minimumLevel: 0,
// maximumLevel: 11,
// rectangle:new Cesium.Rectangle(Cesium.Math.toRadians(114.32), Cesium.Math.toRadians(36.927),
// Cesium.Math.toRadians(114.524), Cesium.Math.toRadians(37.22))
// }))
},
},
};
</script>
<style lang="scss" scoped>
.CesiumOutbox {
width: 100%;
height: 100%;
position: relative;
.cesiumContainerbox {
width: 100%;
height: 100%;
overflow: hidden;
}
.Btnbox {
position: absolute;
top: 15px;
left: 15px;
cursor: pointer;
}
}
</style>