遇到的客户需求
在Cesium的地图上绘制可随缩放变化的网格以及固定的经纬度栅格
需求1:绘制网格
附上代码
var GridImagery = new Cesium.GridImageryProvider();
var imageryLayers = viewer.imageryLayers;
var GridImageryLayer = imageryLayers.addImageryProvider(GridImagery); // 添加网格图层
imageryLayers.raiseToTop(GridImageryLayer); // 将网格图层置顶
代码解释
Cesium本身就具备网格绘制的函数,调用后将该图层置顶即可
需求2:绘制固定的经纬度栅格
附上代码
- 绘制经线
const viewer = new Cesium.Viewer('cesiumContainer');
const entities = viewer.entities;
// 每隔20°绘制一条经度线
for (let lang = -180; lang <= 180; lang += 20) {
let text = "";
if (lang === 0) {
text = "0";
}
text += lang === 0 ? "" : "" + lang + "°";
if (lang === -180) {
text = "";
}
entities.add({
position: Cesium.Cartesian3.fromDegrees(lang, 0),
polyline: {
positions: Cesium.Cartesian3.fromDegreesArray([
lang,
-90,
lang,
0,
lang,
90,
]),
width: 1.0,
material: Cesium.Color.WHITE,
},
label: {
text: text,
verticalOrigin: Cesium.VerticalOrigin.TOP,
font: "12px sans-serif",
fillColor: Cesium.Color.WHITE,
},
});
}
- 绘制纬线
let langS = [];
for (let lang = -180; lang <= 180; lang += 5) {
langS.push(lang);
}
//每隔10°绘制一条纬度线
for (let lat = -80; lat <= 80; lat += 10) {
let text = "";
text += "" + lat + "°";
if (lat === 0) {
text = "";
}
entities.add({
position: Cesium.Cartesian3.fromDegrees(0, lat),
polyline: {
positions: Cesium.Cartesian3.fromDegreesArray(
langS
.map((long) => {
return [long, lat].join(",");
})
.join(",")
.split(",")
.map((item) => Number(item))
),
width: 1.0,
material: Cesium.Color.WHITE,
},
label: {
text: text,
font: "12px sans-serif",
fillColor: Cesium.Color.WHITE,
},
});
}
代码解释
将地图按照经纬度进行分割,随后将分割线给定样式即可