cesium常用方法总结

定位
            window.viewer.camera.flyTo({
                destination: Cesium.Cartesian3.fromDegrees(
                    lon,
                    lat,
                    height
                ),
                orientation: {
                    heading: Cesium.Math.toRadians(0.0),
                    pitch: Cesium.Math.toRadians(-40.0),
                    roll: 0.0,
                },
                duration: 0,
            })
            window.viewer.camera.setView()

        // 带倾斜角度的地图定位
        flyto(coord = [116.405285, 39.904989], height = 60000) {
            // 初始定位
            window.viewer.camera.flyTo({
                destination: Cesium.Cartesian3.fromDegrees(
                    coord[0],
                    coord[1],
                    height
                ),
                orientation: {
                    heading: Cesium.Math.toRadians(0.0),
                    pitch: Cesium.Math.toRadians(-40.0),
                    roll: 0.0,
                },
                duration: 0,
            });
            /**
             * 原理:获取相机坐标,地图中心点坐标,计算偏移量,重新移动相机
             */
            // 当前相机坐标
            let p = window.viewer.camera._positionCartographic;
            // 屏幕中心点坐标
            let _center = new Cesium.Cartesian2(1920 / 2, 1080 / 2);
            const ellipsoid = window.viewer.scene.globe.ellipsoid;
            let cartesian = window.viewer.camera.pickEllipsoid(
                _center,
                ellipsoid
            );
            let cartographic = ellipsoid.cartesianToCartographic(cartesian);
            // 计算偏移量
            let dx = ((cartographic.longitude - p.longitude) / Math.PI) * 180;
            let dy = ((cartographic.latitude - p.latitude) / Math.PI) * 180;
            let heading = window.viewer.camera.heading;
            let pitch = window.viewer.camera.pitch;
            // 移动
            window.viewer.camera.flyTo({
                destination: Cesium.Cartesian3.fromDegrees(
                    coord[0] - dx,
                    coord[1] - dy,
                    height
                ),
                orientation: {
                    heading: heading,
                    pitch: pitch,
                },
                duration: 0,
            });
        },
上点(广告牌)
let entity= {
     position: Cesium.Cartesian3.fromDegrees(item.lonlat[0], item.lonlat[1]),
     infoData: item,
     billboard: { //图标
         image: item.icon, // 图标
         width: 20, // 宽度 默认原图宽度
         height: 20, // 高度 默认原图高度
         show: true,
         // 图标偏移,调整图片定位,pixelOffset: new Cesium.Cartesian3(24, 43)
         pixelOffset: Cesium.Cartesian2.ZERO,
         eyeOffset: Cesium.Cartesian3.ZERO, // 视野偏移,设置后高度小于该值就看不到这个广告牌
         heightReference: Cesium.HeightReference.NONE, // 高度参考
         horizontalOrigin: Cesium.HorizontalOrigin.CENTER, // 纵向 TOP、CENTER、BASELINE、BOTTOM
         verticalOrigin: Cesium.VerticalOrigin.CENTER, // 横向 LEFT、CENTER、RIGHT
         disableDepthTestDistance: Number.POSITIVE_INFINITY, // 获取或设置从相机的距离,在该距离处禁用深度测试,例如,防止剪切地形。设置为零时,将始终应用深度测试,Number.POSITIVE_INFINITY不会做深度监测。但是该属性会造成label无法显示在图片上
    },
    label:{
        text: "label文字",
        pixelOffset: new Cesium.Cartesian2(0, 0),
        eyeOffset: new Cesium.Cartesian3(0, 0, -1)
        horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
        verticalOrigin: Cesium.VerticalOrigin.CENTER
    }
}
// 添加
viewer.entities.add(entity);
// 隐藏
entity.show = false;
// 移除
viewer.entities.remove(entity);
// 清空地图
viewer.entities.removeAll();
图形
/**
 * 折线
 * @param { Array } positions 轨迹坐标集合
 */
export class HandlePath {
    constructor(positions, color, size) {
        this.positions = positions;
        this.entity = viewer.entities.add({
            type: "path",
            polyline: {
                show: true,
                // clampToGround: true,
                positions: new Cesium.CallbackProperty(() => {
                    return this.positions;
                }, false),
                material: Cesium.Color.fromCssColorString(color),
                width: size,
                height: 0
            }
        });
    }
    getEntity() {
        return this.entity;
    }
}

/**
 * 椭圆
 * @param { Array } positions 绘制圆的两个坐标
 */
export class HandleEllipse {
    constructor(positions, color, size) {
        // 获取圆心坐标
        this.update(positions);
        // let tempLon = Cesium.Math.toDegrees(this.point1.longitude + (this.point2.longitude - this.point1.longitude) / 2),
        //     tempLat = Cesium.Math.toDegrees(this.point1.latitude + (this.point2.latitude - this.point1.latitude) / 2);
        this.entity = viewer.entities.add({
            type: "ellipse",
            position: positions[0],
            ellipse: {
                semiMajorAxis: new Cesium.CallbackProperty(() => {
                    return this.xR >= this.yR ? this.xR : this.yR;
                }, false),
                semiMinorAxis: new Cesium.CallbackProperty(() => {
                    return this.xR <= this.yR ? this.xR : this.yR;
                }, false),
                rotation: new Cesium.CallbackProperty(() => {
                    return this.yR > this.xR ? 1.6 : 0
                }, false), // 如果纵向距离大于横向,旋转椭圆(这个值不是角度,1.6是试出来的,我也不知道为什么)
                numberOfVerticalLines: 64, // 椭圆边数
                material: Cesium.Color.fromCssColorString(color).withAlpha(0),
                outline: true,
                outlineColor: Cesium.Color.fromCssColorString(color),
                outlineWidth: size,
                height: 0,
            }
        });
    }
    // 更新
    update(positions) {
        this.positions = positions;
        this.point1 = viewer.scene.globe.ellipsoid.cartesianToCartographic(positions[0]);
        this.point2 = viewer.scene.globe.ellipsoid.cartesianToCartographic(positions[1]);
        const x1 = Cesium.Math.toDegrees(this.point1.longitude);
        const y1 = Cesium.Math.toDegrees(this.point1.latitude);
        const x2 = Cesium.Math.toDegrees(this.point2.longitude);
        const y2 = Cesium.Math.toDegrees(this.point2.latitude);
        // 横向距离
        this.xR = getFlatternDistance(x1, y1, x2, y1);
        // 纵向距离
        this.yR = getFlatternDistance(x1, y1, x1, y2) * 2;
    }
    // 获取entity
    getEntity() {
        return this.entity;
    }
}

//计算两点间距离
function 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));
}

/**
 * 矩形
 * @param { Array } positions 轨迹坐标集合
 */
export class HandleRect {
    constructor(positions, color, size) {
        this.positions = positions;
        this.entity = viewer.entities.add({
            type: "rect",
            rectangle: {
                coordinates: new Cesium.CallbackProperty(() => {
                    return new Cesium.Rectangle.fromCartesianArray(positions);
                }, false),
                material: Cesium.Color.fromCssColorString(color).withAlpha(0),
                outline: true,
                outlineWidth: size,
                outlineColor: Cesium.Color.fromCssColorString(color),
                height: 0
            }
        });
    }
    getEntity() {
        return this.entity;
    }
}
气泡窗体
        setInfoWindow(divName) {
            let that = this,
                infoWindow = function () {};
            let div = document.createElement('DIV');
            that[divName] = div;
            that[divName].style.position = "absolute";
            this.mapCont.cesiumWidget.container.appendChild(div);
            // 显示隐藏
            infoWindow.setVisible = function (visible) {
                that[divName].style.display = visible ? 'block' : 'none';
                if (!visible) {
                    that[divName].innerHTML = '';
                }
            };
            // 定位弹窗
            infoWindow.showAt = function (position, content) {
                if (position) {
                    this.setVisible(true);
                    if (content) {
                        that[divName].innerHTML = '';
                        that[divName].appendChild(content);
                    }
                    that[divName].style.left = position.x + "px";
                    that[divName].style.top = position.y + "px";
                }
            };
            return infoWindow;
        }
this.infoWindow = this.setInfoWindow("alarmInfoWindow");
this.infoWindow .setVisible(false);
// 监听地图移动事件,实时定位
this.infoWindow.showAt(position, div);
地图事件
window.handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
            // 左键按下
            handler.setInputAction(movement => {
                // 点击位置
                var cartesian = viewer.scene.camera.pickEllipsoid(movement.position, viewer.scene.globe.ellipsoid);
                // 点击实体
                var pick = window.viewer.scene.pick(movement.position);
                var pickedEntity = Cesium.defined(pick) ? pick.id : undefined; //pick.id即为entity
                if (pickedEntity) {
            // dosomething...           
                 }
            }, Cesium.ScreenSpaceEventType.LEFT_DOWN);

            // 鼠标移动
            handler.setInputAction(movement => {
                var cartesian = viewer.scene.camera.pickEllipsoid(movement.endPosition, viewer.scene.globe.ellipsoid);
            }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

            // 鼠标抬起
            handler.setInputAction(movement => { 
            }, Cesium.ScreenSpaceEventType.LEFT_UP);
cesium常用方法总结_第1张图片
image.png
点聚合
        /**@argument
         * 聚合效果-自定义聚合样式
         * @method getDataSource
         */
        getDataSource() {
            var options = {
                camera: window.viewer.scene.camera,
                canvas: window.viewer.scene.canvas,
            };

            let dataSourcePromise = window.viewer.dataSources.add(
                window.dataSourceForCluster
            );

            if (!this.dataSourceCollection) {
                this.dataSourceCollection = new Cesium.DataSourceCollection(
                    "dataSourceCollection"
                );
            }
            this.dataSourceCollection.add(dataSourcePromise);

            dataSourcePromise.then(function (dataSource) {
                var pixelRange = 50;
                var minimumClusterSize = 2;
                var enabled = false;

                dataSource.clustering.enabled = enabled;
                dataSource.clustering.pixelRange = pixelRange;
                dataSource.clustering.minimumClusterSize = minimumClusterSize;

                var removeListener;

                function customStyle() {
                    if (Cesium.defined(removeListener)) {
                        removeListener();
                        removeListener = undefined;
                    } else {
                        removeListener = dataSource.clustering.clusterEvent.addEventListener(
                            function (clusteredEntities, cluster) {
                                let len = clusteredEntities.length;

                                cluster.billboard.show = true;
                                cluster.billboard.id = cluster.label.ids;

                                // cluster.billboard.disableDepthTestDistance = Number.POSITIVE_INFINITY;
                                cluster.billboard.image = require("../assets/image/resi-dialog/numberbg.png");
                                cluster.billboard.width = 90;
                                cluster.billboard.height = 90;

                                cluster.label.show = true;
                                cluster.label.text = len + "";
                                cluster.label.style = Cesium.LabelStyle.FILL;
                                cluster.label.fillColor = Cesium.Color.WHITE;
                                cluster.label.outlineWidth = 4;
                                cluster.label.horizontalOrigin =
                                    Cesium.HorizontalOrigin.CENTER;
                                cluster.label.verticalOrigin =
                                    Cesium.VerticalOrigin.CENTER;
                                cluster.label.disableDepthTestDistance =
                                    Number.POSITIVE_INFINITY;

                                cluster.label.pixelOffset = new Cesium.Cartesian2(
                                    0,
                                    3
                                );
                                cluster.label.eyeOffset = new Cesium.Cartesian3(
                                    0,
                                    0,
                                    -10
                                );

                                if (len < 10) {
                                    cluster.label.font =
                                        "normal 32px MicroSoft YaHei";
                                } else if (len < 100) {
                                    cluster.label.font =
                                        "normal 28px MicroSoft YaHei";
                                } else if (len < 1000) {
                                    cluster.label.font =
                                        "normal 24px MicroSoft YaHei";
                                } else if (len < 10000) {
                                    cluster.label.font =
                                        "normal 20px MicroSoft YaHei";
                                } else {
                                    cluster.label.font =
                                        "normal 16px MicroSoft YaHei";
                                }
                            }
                        );
                    }
                    // force a re-cluster with the new styling
                    // var pixelRange = dataSource.clustering.pixelRange;
                    // dataSource.clustering.pixelRange = 0;
                    // dataSource.clustering.pixelRange = pixelRange;
                }

                // start with custom style
                customStyle();
            });
        }

你可能感兴趣的:(cesium常用方法总结)