learning_cesium/汉江流域.html

334 lines
14 KiB
HTML
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<!DOCTYPE html>
<html lang="en">
<head>
<!-- Use correct character set. -->
<meta charset="utf-8" />
<!-- Tell IE to use the latest, best version. -->
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<!-- Make the application on mobile take up the full browser screen and disable user scaling. -->
<meta
name="viewport"
content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no"
/>
<title>Learning Cesium!</title>
<script src="./Build/Cesium/Cesium.js"></script>
<script src="./js/CesiumPopup/CesiumPopup.js"></script>
<link href="./js/CesiumPopup/custompopup.css" rel="stylesheet" />
<style>
@import url(./Build/Cesium/Widgets/widgets.css);
html,
body,
#cesiumContainer {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
overflow: hidden;
}
</style>
</head>
<body>
<div id="cesiumContainer"></div>
<script>
Cesium.Ion.defaultAccessToken =
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI5ZjRjNTZkNC01NDYxLTRhMjQtOGEwZC1kZjA3YzQ5YTJlZDkiLCJpZCI6MjYwODQsInNjb3BlcyI6WyJhc3IiLCJnYyJdLCJpYXQiOjE1ODcxOTMwODN9.prGsSKyAW_9Ow5zHYPhbm3LsQL-ApQw5-5PNJkDaHi8";
var viewer = new Cesium.Viewer("cesiumContainer", {
geocoder: false, //位置查找
homeButton: false, //视图返回初始位置
sceneModePicker: true, //视角选择器
// baseLayerPicker:false,//底图选择器
navigationHelpButton: false, //导航帮助按钮
animation: false, //动画控制器
// creditContainer:"credit",//版权显示
timeline: false, //时间线
fullscreenButton: false, //全屏控件
vrButton: false,
infoBox:false,
selectionIndicator:false
});
var imageryLayers = viewer.scene.imageryLayers;
//清除影像图层集合中的图层
imageryLayers.removeAll();
// 添加 Mapbox tile provider
const mapboxAccess = "pk.eyJ1IjoicWl1c2hpamllIiwiYSI6ImNsMDNvdDRybDEyc2YzZG9kbWZoY2FuOW0ifQ.4FH-BUupi46Z0zQ-CEm_Ig";
// 样式id查看https://docs.mapbox.com/api/maps/styles/
// URL格式的 mapbox://styles/:owner/:style 其中 :owner 是您的 Mapbox 账户名 :style 是样式 ID 。
// 可选值streets-v10、outdoors-v10 、light-v9、dark-v9、satellite-v9、satellite-streets-v10
// const mapboxStyleImagery = new Cesium.MapboxStyleImageryProvider({
// styleId: "satellite-streets-v10",
// accessToken: mapboxAccess,
// });
// imageryLayers.addImageryProvider(mapboxStyleImagery);
// 加载mapbox中自定义的服务
// https://studio.mapbox.com/tilesets/mapbox.satellite
// mapbox://styles/qiushijie/ckayrgiu2160x1iooym5xshpbmapbox://styles/qiushijie/clboooor3000714mi15y9j6ba
var customMapboxIamgery = new Cesium.MapboxStyleImageryProvider({
// url: "https://api.mapbox.com/styles/v1",
username: "qiushijie",
styleId: "clboooor3000714mi15y9j6ba",
accessToken: mapboxAccess,
scaleFactor: true,
});
imageryLayers.addImageryProvider(customMapboxIamgery);
// 调整整体的亮度
var collection = viewer.scene.postProcessStages;
var silhouette = collection.add(Cesium.PostProcessStageLibrary.createBrightnessStage());
silhouette.enabled = true;
silhouette.uniforms.brightness=0.7;
// 将三维球定位到汉江
viewer.camera.flyTo({
destination: Cesium.Cartesian3.fromDegrees(
110.302,
29.98,
1785000
),
orientation: {
heading: Cesium.Math.toRadians(0),
pitch: Cesium.Math.toRadians(-60.74026687972041),
roll: Cesium.Math.toRadians(0),
},
complete: function callback() {
// 定位完成之后的回调函数
},
});
let handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
handler.setInputAction(function (evt) {
//捕获椭球体,将笛卡尔二维平面坐标转为椭球体的笛卡尔三维坐标,返回球体表面的点
var cartesian3 = viewer.camera.pickEllipsoid(evt.position);
// let cartesian3 = viewer.scene.pickPosition(evt.position);
if (cartesian3) {
//将笛卡尔三维坐标转为地图坐标(弧度)
var cartographic = viewer.scene.globe.ellipsoid.cartesianToCartographic(cartesian3);
//将地图坐标(弧度)转为十进制的度数
var lat_String = Cesium.Math.toDegrees(cartographic.latitude).toFixed(6);
var log_String = Cesium.Math.toDegrees(cartographic.longitude).toFixed(6);
var alti_String = (viewer.camera.positionCartographic.height / 1000).toFixed(2);
console.log(log_String,lat_String)
}
// 获取该位置的所有primitive集合
let picks = viewer.scene.drillPick(evt.position);
let bills = picks.filter(item=>item.primitive instanceof Cesium.Billboard);
if(cartesian3&&bills.length){
let item = JSON.parse(bills[0].id.id);
if(!item.layer||item.layer!="poi") return;
let position = new Cesium.Cartesian3.fromDegrees(item.lng, item.lat,100);
var html = "<div>" +(item.abstract)+"</div>";
// for(let key in fields){
// html += "<div>" + key + " :"+ fields[key] + "</div>"
// }
var a = new CesiumPopup({
title: "龙王庙<span class='location'>定位<i></i></span>",
})
.setPosition(position)
.setHTML(html)
.addTo(viewer)
a.on("close", function () {
console.log("close");
});
a.on("open", function () {
console.log("open");
});
a.removeClass("cesium-popup-panel").addClassName("cesium-popup-hanjiang")
}
}, Cesium.ScreenSpaceEventType.LEFT_CLICK)
addHanRiver();
// createPoiLabel("龙王庙")
const pois=[
{name:"龙王庙",abstract:"汉江上游全场956千米集水面积95220平方千米敢流呈东西走向穿行于秦岭、大巴山之间沿途峡谷盆地交替河床多为卵石、砾石与基岩组成河道比降大。",lng:114.285869 ,lat: 30.569577,icon:""},
{name:"嶓冢山",abstract:"汉江上游全场956千米集水面积95220平方千米敢流呈东西走向穿行于秦岭、大巴山之间沿途峡谷盆地交替河床多为卵石、砾石与基岩组成河道比降大。",lng:106.24576 ,lat:33.07099,icon:""},
{name:"上游段",abstract:"汉江上游全场956千米集水面积95220平方千米敢流呈东西走向穿行于秦岭、大巴山之间沿途峡谷盆地交替河床多为卵石、砾石与基岩组成河道比降大。",lng:1,lat:1,}
]
addPoiBill(pois[0])
function addPoiBill(data){
let image = createPoiLabel(data.name)
let entity = viewer.entities.add({
id:JSON.stringify({...data,layer:"poi"}),
position: Cesium.Cartesian3.fromDegrees(data.lng, data.lat,0),
billboard: {
eyeOffset: new Cesium.Cartesian3(0.0, 1.0, 0.0),
image: image, // default: undefined
show: true, // default
// pixelOffset:new Cesium.Cartesian2(-60, 0),
width: 120, // default: undefined
height: 80, // default: undefined
disableDepthTestDistance : Number.POSITIVE_INFINITY,
// distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
// 10.0,
// 30000.0
// ), //根据到相机的距离确定可见性。
scaleByDistance: new Cesium.NearFarScalar(10, 1, 3000000, 0.0),
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
heightReference :Cesium.HeightReference.CLAMP_TO_GROUND
},
});
viewer.flyTo(entity)
}
async function createPoiLabel(label){
// 创建画布对象
let canvas = document.createElement('canvas');
let len = label.split("").length,width=120,height=80;
canvas.width = 17*len>width?17*len:width;
canvas.height = height;
let ctx = canvas.getContext("2d");
// ctx.fillStyle = '#000';
// ctx.fillRect(0, 0, canvas.width, canvas.height);
const url1 = 'http://127.0.0.1:5502/images/hanjiang/poi_label.png';
const url2 = 'http://127.0.0.1:5502/images/hanjiang/poi_location.png'
let image1 = await new Cesium.Resource.fetchImage(url1);
ctx.drawImage(image1, 0, 0, 120, 32)//改变图片大小到1080*980
ctx.fillStyle = "#CFF8FF";
ctx.lineHeight = 17;
ctx.font = '700 17px "fangsong"';
ctx.textBaseline = "middle";
ctx.fillText(label, 30, 15);
let image2 = await new Cesium.Resource.fetchImage(url2);
ctx.drawImage(image2, 44, 37, 32, 42)
return canvas;
}
function example(){
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const name = "龙王庙"
canvas.width = 120;
canvas.height = 80;
var img = new Image()
img.src = 'http://127.0.0.1:5502/images/hanjiang/poi_label.png'
//图片加载完后将其显示在canvas中
img.onload = function(){
//context.drawImage(this, 0, 24)
ctx.drawImage(this, 0, 0, 120, 32)//改变图片大小到1080*980
ctx.fillStyle = "#CFF8FF";
ctx.lineHeight = 17;
ctx.font = '700 17px "fangsong"';
ctx.textBaseline = "middle";
ctx.fillText(name, 30, 15);
var img2 = new Image()
img2.src = 'http://127.0.0.1:5502/images/hanjiang/poi_location.png';
img2.onload = function(){
ctx.drawImage(this, 44, 37, 32, 42)//改变图片大小到1080*980
}
}
}
function combineIconAndLabel(url, label,width,height) {
// 创建画布对象
let canvas = document.createElement('canvas');
let len = label.split("").length;
canvas.width = 16*len>width?16*len:width;
canvas.height = height + 22;
let ctx = canvas.getContext("2d");
let promise = new Cesium.Resource.fetchImage(url).then(image => {
// 异常判断
try {
ctx.drawImage(image, (canvas.width/2)-width/2, 20);
} catch (e) {
console.log(e);
}
// 渲染字体
// font属性设置顺序font-style, font-variant, font-weight, font-size, line-height, font-family
ctx.fillStyle = Cesium.Color.WHITE.toCssColorString();
ctx.font="16px FANGSONG"
ctx.fillText(label, 0, 15);
return canvas;
});
return promise;
}
async function getHanData(){
const url = "http://121.33.231.74:5097/geoserver/iot/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=iot%3Ahanjiang&maxFeatures=999&outputFormat=application%2Fjson";
return await fetch(url).then(res=>res.json())
}
async function addHanRiver(){
const result = await getHanData();
console.log(result)
let primitives = viewer.scene.primitives.add(
new Cesium.PrimitiveCollection()
);
// primitives.show = false;
window.primitives = primitives;
result.features.forEach((feature) => {
addWaterFeature(primitives,feature);
});
}
function addWaterFeature(primitives,feature) {
let geometryType = feature.geometry.type;
let coord = feature.geometry.coordinates;
let geometryName = feature.geometry_name;
if (geometryType == "MultiPolygon") {
coord.forEach((polygon) => {
let outBoundary = null;
let holes = null;
// if(polygon.length==1){
outBoundary = new Cesium.PolygonHierarchy(
Cesium.Cartesian3.fromDegreesArray(polygon[0].flat(2))
);
// }
primitives.add(
new Cesium.Primitive({
geometryInstances: new Cesium.GeometryInstance({
geometry: new Cesium.PolygonGeometry({
polygonHierarchy: outBoundary,
}),
attributes: {
// 通过attributes属性统一指定线段颜色
color: Cesium.ColorGeometryInstanceAttribute.fromColor(
new Cesium.Color(1.0, 0, 0, 1.0)
),
},
id: "面要素",
}),
appearance: new Cesium.EllipsoidSurfaceAppearance({
material: new Cesium.Material({
fabric: {
type: "Water",
uniforms: {
// 水的基本颜色
baseWaterColor: new Cesium.Color(
64 / 255.0,
157 / 255.0,
253 / 255.0,
0.5
),
// 水法向摄动的法线图
normalMap:
"./Build/Cesium/Assets/Textures/waterNormals.jpg",
// 波纹数量
frequency: 1000.0,
// 动画速度
animationSpeed: 0.002,
// 振动的幅度
amplitude: 150,
// 镜面反射的强度
specularIntensity: 1,
},
},
}),
faceForward: true,
}),
})
);
});
}
}
</script>
</body>
</html>