Cesium之地圖研究


Cesium之地圖研究

 作者:璐璐

##### entities(可添加 point、polyline、billboard、wall、model、polylineVolume等等)

* 添加點

```js
viewer.entities.add({
    name: '',
    position: Cesium.Cartesian3.fromDegrees(lon, lat, 0),
    point: {
        show: true, // default
        color: ,
        pixelSize: 15, // default: 1
        outlineWidth: 0
        // scaleByDistance: new Cesium.NearFarScalar(
        //   10,
        //   10,
        //   1200000,
        //   5
        // )
    }
})
```

* 添加線

```js
// data = [lon1,lat1,h1,lon2,lat2,h2]
viewer.entities.add({
    name : 'line',
    polyline : {
        positions : Cesium.Cartesian3.fromDegreesArrayHeights(data),
        width : 4,
        material : this.getMaterial2(item, color)
    }
})
```

* 添加圖片 Billboard

```js
viewer.entities.add({
    name: '',
    position: Cesium.Cartesian3.fromDegrees(lon, lat, heights),
    billboard: {
        image: '/images/1.png',
        width: 300,
        height: 150,
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
        horizontalOrigin: Cesium.HorizontalOrigin.LEFT
    }
})
```

* 添加牆 Wall

```js
viewer.entities.add({
    name: '',
    wall: {
        positions: Cesium.Cartesian3.fromDegreesArrayHeights(dataArr),
        // 漸變色
        material: new Cesium.ImageMaterialProperty({
            //  fe3b3c    10f7b0    fffd8f
            //添加回調
            image:
            types == 1
            ? red1
            : types == 2
            ? red11
            : types == 3
            ? light4
            : purple,
            repeat: new Cesium.Cartesian2(50, 1.0),
            transparent: true
        })
        // outlineColor: Cesium.Color.WHITE,
        // outlineWidth: 30
        // 純色
        // material: colors,
    }
    // // 添加其他屬性
    // properties: {
    //   name: v.name ? v.name : '--',
    //   address: v.address ? v.address : '--'
    // }
})
```

* 添加實體

```js
// 將經緯度坐標轉換為三維空間坐標
var position = Cesium.Cartesian3.fromDegrees(120, 27, 1000);
var heading = Cesium.Math.toRadians(135);
var pitch = Cesium.Math.toRadians(10);
var roll = Cesium.Math.toRadians(10);
var hpr = new Cesium.HeadingPitchRoll(heading, pitch, roll);
var orientation = Cesium.Transforms.headingPitchRollQuaternion(
    position,
    hpr
);
viewer.entities.add({
    //模型所在位置
    position: position,
    orientation: orientation,
    model: {
        uri: '/gltf/yuan.gltf',
        minimumPixelSize: 100,
        maximumScale: 50,
        scale: 100,
        show: true,
        color: Cesium.Color.fromCssColorString('#ff5b3d').withAlpha(0.5),
        // silhouetteColor: Cesium.Color.fromAlpha(Cesium.Color.fromCssColorString('#ffba0c'),0.4),
        // silhouetteSize: 5,
    }
})
```

* 刪除

```js
// 1
viewer.entities.removeById(id)
// 2
removeEntities(name) {
    let viewer = this._earth.czm.viewer
    let entities = viewer.entities._entities._array
    for (var i = 0; i < entities.length; i++) {
        if (entities[i]._name == name) {
            viewer.entities.remove(entities[i])
            i--
        }
    }
}
```

##### dataSource

* 直接加載

```js
Cesium.GeoJsonDataSource.load('/topuLine/roomLine.json').then(dataSource => {
    dataSource.name = "Expressway";
    viewer.dataSources.add(dataSource);
    let entities = dataSource.entities.values;
    for (let i = 0; i < entities.length; i++) {
        let entity = entities[i];
        entity.material = Cesium.Material.fromType('Color');
        entity.material.uniforms.color = new Cesium.Color(1.0, 1.0, 0.0, 0.1);
        // Cesium.Color.fromCssColorString(lineColor)
        entity.polyline.width = 2;
        entity.polyline.translucent  true;
    }
})
```

* 先創建 dataSource 實體集合,再添加

```js
// 創建實體集合
var dataSource = new Cesium.CustomDataSource('lines');
for (let i=0; i< lineArr.length;i++) {
    dataSource.entities.add({
        polylineVolume: {
            positions: Cesium.Cartesian3.fromDegreesArrayHeights(lineArr[i]),
            // shape: computeCircle(60000), // 圓柱子
            // shape: computeStar(3, 26000, 50000), // 三角形柱子
            // shape: computeStar(2, 50000, 50000), // 正方型柱子
            // shape: computeStar(5, 40000, 50000), // 五邊形柱子
            shape: computeStar(5, 4000, 5000), // 五邊形柱子
            // shape: computeStar(5, 70000, 40000), // 五角星柱子
            material: stripeMaterial,
            outlineColor: Cesium.Color.WHITE,
            outlineWidth: 1
        }
    });
}
return viewer.dataSources.add(dataSource)
```

##### primitives

```js
let tiles = new Cesium.Cesium3DTileset({
    url: '/tileset/tileset.json',
    maximumScreenSpaceError: 1, // Temporary workaround for low memory mobile devices - Increase maximum error to 8.
    maximumNumberOfLoadedTiles: 1000 // Temporary workaround for low memory mobile devices - Decrease (disable) tile cache.
})
tiles.readyPromise.then(arg => {})
viewer.scene.primitives.add(tiles)
```

##### 定位

```js
//
viewer.zoomTo(viewer.entities)
// 
viewer.scene.camera.flyTo({
    destination: Cesium.Cartesian3.fromDegrees(120.272496,31.483777,1000),
    orientation: {
        heading: Cesium.Math.toRadians(0), //左右平移
        pitch: Cesium.Math.toRadians(-35), // 水平翻轉
        roll: Cesium.Math.toRadians(0) // 垂直翻轉
    },
    duration: 2 //定位的時間間隔
})
```

* 各種坐標轉換

```js
// 經緯度 --> 世界坐標
var ellipsoid = viewer.scene.globe.ellipsoid
var cartographic = Cesium.Cartographic.fromDegrees(lon, lat, 0)
var cartesian3 = ellipsoid.cartographicToCartesian(cartographic)
// 世界坐標 --> 屏幕坐標
var cartesian2 = Cesium.SceneTransforms.wgs84ToWindowCoordinates(
    viewer.scene,
    cartesian3
)

// position 世界坐標 --> 經緯度 lon,lat
var ellipsoid = viewer.scene.globe.ellipsoid
var cartesian3 = viewer.camera.pickEllipsoid(position,ellipsoid)
var cartographic = ellipsoid.cartesianToCartographic(cartesian3)
var lon = Cesium.Math.toDegrees(cartographic.longitude)
var lat = Cesium.Math.toDegrees(cartographic.latitude)
```

#### earthSdk (經緯度為弧度)

##### 常規

* 添加點

```js
const objConfig = {
    name: 'Pin1',
    xbsjType: 'Pin',
    position: [lon, lat, 500],
    near: 20000,
    imageUrl: '/images/earth/img/station.png',
    disableDepthTestDistance: 0,
    scale: 1,
    origin: [5, 5] // 類似 offset
}
const pin = new XE.Obj.Pin(earth)
pin.xbsjFromJSON(objConfig)
pin.onclick = () => {
    // 點擊事件邏輯
}
```

* 添加線

```js
// 處理數據
var busLines = []
var p = [
    [
        [2.120576951415724, 0.5453286305283411, 0],
        [2.1206180324809942, 0.5452742515355276, 0],
        [2.1206522870077222, 0.5452127930893627, 0],
        [2.1206589437154424, 0.5451630655115893, 0],
        [2.1207314498206467, 0.5450382941603948, 9.313225746154785e-10]
    ]
]
let timeDuration = 10.0
let moveBaseDuration = 4.0

busLines = p.map(e => {
    return {
        positions: e.map(ee => [ee[0], ee[1]]),
        color: [
            Math.random() * 0.5 + 0.5,
            Math.random() * 0.8 + 0.2,
            0.0,
            1.0
        ],
        width: 2.0,
        startTime: timeDuration * Math.random(),
        duration: moveBaseDuration + 1.0 * Math.random()
    }
})

// 添加線
const odlines = new XE.Obj.ODLines(earth);
odlines.data = busLines
odlines.timeDuration = timeDuration
odlines.playing = true
```

* 添加 primitives

```js
// 添加一些復雜集合體,柱體、錐體等
const renderState = XE.Obj.CustomPrimitive.getRenderState(true,true)
const evalString = `
    p.canvasWidth = 1;
    p.canvasHeight = 256;
    p.drawCanvas(ctx => {
        ctx.clearRect(0, 0, 1, 256);

        var lingrad2 = ctx.createLinearGradient(0,0,0,256);
        lingrad2.addColorStop(0, 'rgba(255,255,255,0)');
        lingrad2.addColorStop(1, 'rgba(255,255,255,1)');

        ctx.fillStyle = lingrad2;
        ctx.fillRect(0, 0, 1, 256);
    }); 
`;

const preUpdateEvalString = `
    if (typeof p.dt === 'undefined') p.dt = 0.0;
    p.dt += 0.01 * 0.3;
    if (p.dt > 1.0) {
        p.dt = 0.0;
    }

    const b = (1.0-Math.cos(p.dt*Math.PI*2.0))*0.5;
    p.scale[0] = p.scale[1] = 200 * (1.0-Math.cos(p.dt*Math.PI))*0.5;
    p.scale[2] = 50 * b;
    p.color[3] = 2.0 * b;
`;

const config = {
    evalString,
    preUpdateEvalString,
    position,
    scale: [200, 200, 100],
    positions: positions, // 位置數組 [0,-1,0, 0,1,0, 0,1,2, 0,-1,2,]  cylinder.positions or unitSquare.positions 等等
    sts: sts,             // 紋理坐標數組 [0,0, 1,0, 1,1, 0,1, ]
    indices: indices,     // 索引數組 [0, 1, 2, 0, 2, 3,]
    renderState: renderState,
    canvasWidth: 1,
    canvasHeight: 256,
    color: [0.5, 0.8, 1, 2],
}

const p = new XE.Obj.CustomPrimitive(earth);
p.xbsjFromJSON(config);
```

* 其他

```js
// XE.Obj.CustomPrimitive.Geometry.unitSquare
// XE.Obj.CustomPrimitive.Geometry.createCylinder(1.0, 1.0, 1.0, 30)
// XE.Obj.CustomPrimitive.Geometry.unitBillboard
```

##### mapV (處理大量數據)

```js
var dataSet = new mapv.DataSet(data)
var options = {
    fillStyle: 'rgba(55, 50, 250, 0.8)', // 填充顏色
    shadowColor: 'rgba(255, 250, 50, 1)', // 投影顏色
    shadowBlur: 5, // 投影模糊級數
    max: 100, // 數值最大值范圍
    size: 42, // 大小值
    label: {
        // 是否顯示文字標簽
        show: true,
        fillStyle: 'white', // 填充顏色
        // shadowColor: 'yellow',
        font: '18px Arial'
        // shadowBlur: 10,
    },
    globalAlpha: 0.7, // 透明度
    gradient: {
        0.25: 'rgb(87,119,232)',
        0.55: 'rgb(76,117,189)',
        0.85: 'rgb(255,216,0)',
        1.0: 'rgb(227,117,120)'
    }, // 漸變色
    draw: 'honeycomb' // 蜂窩狀展示
    // eg: 'honeycomb'/'simple'/'circle'/'rect'/'intensity'/'heatmap'/'category'/'bubble'/'choropleth'
    // eg: 'grid'/'cluster'/'text'/'icon'/'clip'/'time'/
}

XE.mixins.mapVLayer(viewer, dataSet, options)
```



### 參考

1. [cesium 沙盒](https://sandcastle.cesium.com/?)

2. [cesium 官方文檔](https://cesium.com/docs/cesiumjs-ref-doc/)
3. [cesium 中文文檔](http://cesium.xin/cesium/cn/Documentation1.62/)    **版本可能滯后**
4. [cesium文檔(火星科技)](http://cesium.marsgis.cn/go.html?id=12)
5. [earthSdk 沙盒](http://earthsdk.com/v/last/Apps/Examples/?menu=true&url=./startup-createEarth.html)
6. [earthSdk 文檔](http://www.earthsdk.com/#/help)
7. [百度mapV示例](https://mapv.baidu.com/examples/)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM