当前位置:网站首页>Cesium view switching, locating, reading files, building data sources, entity control, model control, etc

Cesium view switching, locating, reading files, building data sources, entity control, model control, etc

2022-06-13 08:45:00 Dependency_ Lai

Flight positioning method

viewer class
viewer.flyTo(target, options) With flying animation effect ,pitch It is recommended to use... When it is not the default value
viewer.zoomTo(target, options) Locate directly to the target point
viewer.trackedEntity = entity The perspective will be locked to the target entity
It can be done by viewer.trackedEntity = undefined Unlock the view angle
camera class
viewer.camera.flyTo(options) With flying animation effect
viewer.camera.flyToBoundingSphere(boundingSphere, options) With flying animation effect
viewer.camera.setView(options)
viewer.camera.lookAt(target, offset) The viewing angle will be locked to the target position
viewer.camera.lookAtTransform(transform, offset) Commonly used in four-dimensional matrix positioning
It can be done by viewer.camera.lookAtTransform(Matrix4.IDENTITY) Cancel lookAt View lock
viewer.camera.twistLeft(cMath.PI_OVER_SIX) Radian system , The camera rotates counterclockwise by a certain angle
viewer.camera.twistRight(cMath.PI_OVER_SIX) Radian system , The camera rotates clockwise by a certain angle
viewer.camera.zoomIn(5000) The camera zooms in a certain distance
viewer.camera.zoomOut(5000) The camera shrinks a certain distance
viewer.camera.move(direction, amount) The camera moves a certain distance in the specified direction
viewer.camera.moveForward(5000) Camera back a certain distance
viewer.camera.moveBackward(5000) The camera moves forward a certain distance
viewer.camera.moveUp(5000) The camera moves up a certain distance
viewer.camera.moveDown(5000) The camera moves down a certain distance
viewer.camera.moveLeft(5000) The camera moves a certain distance to the left
viewer.camera.moveRight(5000) The camera moves a certain distance to the right
Positional arguments
pitch: Pitch angle , Default -90( radian )—— Back and forth somersault
heading: Yaw angle , Default 0( radian )—— Left and right
roll: Roll angle , Default 0( radian )—— Side somersault
range: Range ( rice )—— The distance from the target

Fly to perspective

		// Knowing the latitude and longitude 
	    /* viewer.camera.flyTo({ destination : Cesium.Cartesian3.fromDegrees(116.523753404617, 40.2340042591095, 1000.0), orientation: {"pitch":-0.5450456670292048,"heading":0.018399360640374063,"roll":0.0018415377068681238} });*/
	     // Knowing Descartes' case 
	    viewer.camera.flyTo(
	        {
    
	            "destination": {
    "x": -2177577.305512763, "y": 4362932.485127032, "z": 4098026.456405151},
	            "orientation":{
    "pitch": -1.4864402773467176, "heading": 4.747122814066271, "roll": 6.243888148462918}
	        });

		// Fly to the world 
		viewer.camera.flyTo({
    
		   destination: Cesium.Rectangle.fromDegrees(30, 0, 180, 60),
		   complete: () => {
    
		       // Load other data 
		   },
		});

Calculate longitude and latitude according to the range

/*** *  Fly according to the range  * @param {*} data = [ [116.52453466251528, 40.233651754887056, 1], [116.52453466251528, 40.233471232847634, 1], [116.524521776882, 40.233471232847634, 1], [116.524521776882, 40.233651754887056, 1] ] */
getExtent(data) {
    
    return new Promise(function (resolve) {
    
        var xmin, xmax, ymin, ymax;
        data.forEach(i => {
    
            if (!xmin && !xmax && !ymin && !ymax) {
    
                xmin = Number(i[0]);
                xmax = Number(i[0]);
                ymin = Number(i[1]);
                ymax = Number(i[1]);
            } else {
    
                if (xmin > Number(i[0])) {
    
                    xmin = Number(i[0]);
                }
                if (xmax < Number(i[0])) {
    
                    xmax = Number(i[0]);
                }
                if (ymin > Number(i[1])) {
    
                    ymin = Number(i[1]);
                }
                if (ymax < Number(i[1])) {
    
                    ymax = Number(i[1]);
                }
            }
        });
        if (!xmin && !xmax && !ymin && !ymax) {
    
            resolve();
        } else {
    
            resolve({
    
                xmin: xmin,
                ymin: ymin,
                xmax: xmax,
                ymax: ymax
            });
        }
    });
}

Fly according to the range calculation results

/*** *  Construct a new entity flight based on the range data  * @param {*} data = { xmin: 116.52453466251528, ymin: 40.233651754887056, xmax: 116.52453476251528, ymax: 40.233651764887056 } */
flyToExtent(data) {
    
    let viewer = getViewer();
    // Construct a new entity , Transparency is 0
    let loactionTectEntity = viewer.entities.add({
    
        rectangle: {
    
            coordinates: Cesium.Rectangle.fromDegrees(
                data.xmin,
                data.ymin,
                data.xmax,
                data.ymax
            ),
            material: Cesium.Color.GREEN.withAlpha(0),
            height: 1,
            outline: false,
        },
    });
    let pro = viewer.flyTo(loactionTectEntity, {
    
        duration: 3,
        offset: new Cesium.HeadingPitchRange( Cesium.Math.toRadians(45),  Cesium.Math.toRadians(-35.0),200)
    });
    pro.then(() => )
    	// Remove the new entity 
        viewer.entities.remove(loactionTectEntity);
    });
}

Read json data

/** * json File read  * @param {*} url json The address of  */
jsonParse(url) {
    
    return new Promise((resolve, reject) => {
    
        let features = null;
        Cesium.Resource.fetchJson({
    
            url: url,
        }).then((val) => {
    
            if (val.features && val.features.length > 0) {
    
                features = val.features;
            }
            resolve(features);
        });
    });
}

adopt geojson Data acquisition data source

/** * json File read  * @param {*} url json The address of  */
jsonToDataSource(url) {
    
	return new Promise((resolve, reject) => {
    
		Cesium.GeoJsonDataSource.load(url, {
    
	        clampToGround: true,
	      }).then(datasource => {
    
	        resolve(datasource );
	    });    
    });   
}

Construct data source

/** * Cesium General method of data source construction in  * @param {*} datasouceName: The entity name  * -------------------------------------------------------------------------------------------- */
map_common_addDatasouce(datasouceName) {
    
    let datasouce = getViewer().dataSources._dataSources.find(t => {
    
        return t && t.name == datasouceName;
    });
    if (!datasouce) {
    
        datasouce = new Cesium.CustomDataSource(datasouceName);
        getViewer().dataSources.add(datasouce);
    }
    return datasouce;
}

Read json Data loading entity

jsonParse("/json/home/ The Beijing municipal .json").then((val) => {
    
        if (val && val.length > 0) {
    
            val.forEach((el) => {
    
            	// adopt CustomDataSource Construct data source 
            	let datasource = map_common_addDatasouce(datasourceName.BEIJING_LINE);
                datasource.entities.add(new Entity({
    
                    //Entity Entity 
                    /*polygon: { hierarchy: Cesium.Cartesian3.fromDegreesArray(positions), material: Cesium.Color.fromRandom() }*/
                }))
                // adopt entities Entity 
                /*getViewer().entities.add( new Entity({ //Entity Entity  /*polygon: { hierarchy: Cesium.Cartesian3.fromDegreesArray(positions), material: Cesium.Color.fromRandom() }*/
			        })
			    );*/
            })  
        }
    })

adopt GeoJsonDataSource Get the data source loading entity

jsonToDataSource("/json/home/ The Beijing municipal .json").then((datasource)=>{
    
        getViewer().dataSources.add(datasource);
        let entities = datasource.entities.values;
        for (let index = 0; index < entities.length; index++) {
    
            const entity = entities[index];
            if (entity.polygon) {
    
            	//Entity Solid styles 
                //entity.polygon.material = Cesium.Color.fromRandom();
            }
        }
    })

Clear entities

/** * @param {*} datasouceName: The entity name  * -------------------------------------------------------------------------------------------- */
datasouceIsRemove(datasouceName) {
    
    let datasouce = map_common_addDatasouce(datasouceName);
    if (datasouce !== null || datasouce !== undefined) {
    
       datasouce.entities.removeAll();
    }
}

Control entity visibility

/** *  control datasouceName Show hidden  * @param {*} datasouceName: The entity name  * -------------------------------------------------------------------------------------------- */
datasouceIsShow(datasouceName, isShow, id = '') {
    
	let datasouce = map_common_addDatasouce(datasouceName);
    if (datasouce !== null || datasouce !== undefined) {
    
        if (!!id) {
    // Control an entity 
            let obj = datasouce.entities.values.find(item => item.properties.details._value.id === id);
            if (obj) {
    
                obj.show = isShow
            }
        } else {
    // Control a certain type of entity 
            datasouce.entities.values.forEach(item=>{
    
                item.show = isShow
            })
        }
    }
}

Clear model

/** * @param {*} modelType: Model type  * -------------------------------------------------------------------------------------------- */
removeModel(modelType) {
    
    let viewer = getViewer();
    let model = viewer.scene.primitives._primitives.filter(t => {
    
        return t && t.type === modelType;
    });
    if (model && model.length) {
    
        model.forEach(item => {
    
            viewer.scene.primitives.remove(item);
        })
    }
}

control gltf Some models are explicit and implicit

/** * @param {*} * modelType: Model type  * data: { names: ['name1'], show: false } */
controlGltfModelShow(modelType, data) {
    
    let viewer = getViewer();
    let model = viewer.scene.primitives._primitives.filter(t => {
    
        return t && t.type === modelType;
    });
    if (model && model.length) {
    
        model.forEach(item => {
    
            item._nodeCommands.forEach(c => {
    
                if (!data.show) {
    
                	//c.command.owner.node.name:  Sub model name 
                    c.show = !(data.names.includes(c.command.owner.node.name));
                } else {
    
                    c.show = true
                }
            })
        })
    }
}

control gltf Model style

/** * @param {*} * modelType: Model type  * data: { show: true, ids: ['id1'] } */
controlGltfModelStyle(modelType, data) {
    
    let viewer = getViewer();
    let model = viewer.scene.primitives._primitives.filter(t => {
    
        return t && t.type === modelType;
    });
    if (model && model.length) {
    
        let x = 1;
        let flog = true
        // Change style dynamically 
        viewer.scene.preUpdate.addEventListener(() => {
    
            model.forEach(item => {
    
            	//item.modelId: gitf Model custom properties 
                if (data.show && item.modelId && data.ids.includes(item.modelId)) {
    
                    // Change transparency dynamically 
                    if (flog) {
    
                        x = x - 0.03;
                        if (x <= 0.2) {
    
                            flog = false;
                        }
                    } else {
    
                        x = x + 0.03;
                        if (x >= 0.8) {
    
                            flog = true;
                        }
                    }
                    item.color =  Cesium.Color.RED.withAlpha(x)
                } else {
    
                    item.color = Cesium.Color.fromCssColorString(`rgb(255, 225, 225)`).withAlpha(1)
                }
            })
        });
    }
}

control 3dTiles Some models are explicit and implicit

/** * @param {*} * modelType: Model type  * data: { names: ['name1'], show: false } */
export function control3dTilesModelShow(modelType, data) {
    
    let viewer = getViewer();
    let model = viewer.scene.primitives._primitives.filter(t => {
    
        return t && t.type === modelType;
    });
    if (model && model.length) {
    
        model.forEach(item => {
    
            item.style = new Cesium.Cesium3DTileStyle({
    
                show: {
    
                    evaluate: (feature) => {
    
                        if (!data.show) {
    
							//feature.getProperty("name"):  Sub model name 
                            return !(data.names.includes(feature.getProperty("name")))
                        } else {
    
                            return true
                        }
                    }
                }
            });
        })
    }
}

control 3dTiles Some model styles

/** * @param {*} modelType: Model type  data: { show: true, names: ['name1'] } */
var defaultStyle = []; 
control3dTilesModelStyle(modelType, data) {
    
    let viewer = getViewer();
    let model = viewer.scene.primitives._primitives.filter(t => {
    
        return t && t.type === modelType;
    });
    if (model && model.length) {
    
        if (data.show) {
    
            defaultStyle = []
        }
        let x = 1;
        let flog = true
        // Change style dynamically 
        viewer.scene.preUpdate.addEventListener(() => {
    
            model.forEach(item => {
    
                if (data.show) {
    
                    // Save default styles 
                    defaultStyle.push({
    
                        url: item._url,
                        style: new Cesium.Cesium3DTileStyle()
                    })
                    // Change transparency dynamically , Achieve flashing animation effect 
                    if (flog) {
    
                            x = x - 0.03;
                            if (x <= 0.2) {
    
                                flog = false;
                            }
                        } else {
    
                            x = x + 0.03;
                            if (x >= 0.8) {
    
                                flog = true;
                            }
                        }
                        item.style = new Cesium.Cesium3DTileStyle({
    
                            color: {
    
                                evaluateColor: function (feature, result) {
    
                                	//feature.getProperty("name"):  Sub model name 
                                    if (data.names.includes(feature.getProperty("name"))) {
    
                                        return Cesium.Color.RED.withAlpha(x)
                                    }
                                    return Cesium.Color.WHITE;
                                }
                            }
                        });
                } else {
    
                    let obj = defaultStyle.find(sty => sty.url === item._url)
                    if (obj) {
    
                        item.style = obj.style
                    }
                }
            })
        });
        // Set fixed style 
        /*model.forEach(item => { if (data.show) { // Save default styles  defaultStyle.push({ url: item._url, style: new Cesium.Cesium3DTileStyle() }) item.style = new Cesium.Cesium3DTileStyle({ color: { evaluateColor: function (feature, result) { //feature.getProperty("name"):  Sub model name  if (data.names.includes(feature.getProperty("name"))) { return Cesium.Color.RED.withAlpha(0.5) } return Cesium.Color.WHITE; } // Set the color according to the height  /*conditions : [ ['${Height} >= 80', 'color("purple", 0.5)'], ['${Height} >= 30', 'color("red")'], ['true', 'color("blue")'] ]*/
                        }
                    });
            } else {
    
                let obj = defaultStyle.find(sty => sty.url === item._url)
                if (obj) {
    
                    item.style = obj.style
                }
            }
        })*/
        // Get submodels feature
		/* let curModels= viewer.scene.primitives._primitives.filter(t => { return t && t.type === modelType; }); curModels.forEach(model => { if (model.root && model.root.children && model.root.children.length) { model.root.children.forEach(modelChild => { if (modelChild.content && modelChild.content.featuresLength) { let featuresLength = modelChild.content.featuresLength; for (let i = 0; i < featuresLength; i++) { let feature = modelChild.content.getFeature(i); //feature.getProperty("name"):  Sub model name  // Change model color  //feature.color = Cesium.Color.fromCssColorString("#faff12").withAlpha(0.8) // Restore model color  //feature.color = new Cesium.Color(1, 1, 1, 1); } } }) } })*/
        
    }
}

 Insert picture description here

原网站

版权声明
本文为[Dependency_ Lai]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202270538334822.html