cesium号称是集显示时空数据于一体的三维引擎。空间数据的展示我们已经见到,对于时间上的数据,我觉得CallbackProperty是最大功臣。因为使用CallbackProperty,cesium中一切可视化的要素都可以与时间联系起来。
定义CallbackProperty函数代码如下:
new Cesium.CallbackProperty(getEndPoint, isConstant)
function getEndPoint (time, result) {
endLongitude = startLongitude - 0.001 * Cesium.JulianDate.secondsDifference(time, startTime);
return Cesium.Cartesian3.fromDegreesArray(
[startLongitude, startLatitude, endLongitude, startLatitude],
Cesium.Ellipsoid.WGS84,
result
);
}
CallbackProperty(getEndPoint, isConstant)中,isConstant是用来判断函数返回的值是否要更新到渲染中去。判断的标准是否很简单,就是预先指定返回的值是变还是不变的。例如代码中每次返回的坐应该都是变的,所以应该设置成false,也是就,返回的值是连续变化的。当返回不变的值时,即可不更新渲染数据(从实验得到的结果是这样的,不知道理解是否正确)。
下面的代码实例就是利用CallbackProperty函数获不断更新线段的终点,并在线段中点位置显示线段的长度。
var startLatitude = 35;
var startLongitude = 120;
var endLongitude;
var startTime = Cesium.JulianDate.now();
var isConstant = false;
// use scratch object to avoid new allocations per frame.
var endCartographic = new Cesium.Cartographic();
var scratch = new Cesium.Cartographic();
var geodesic = new Cesium.EllipsoidGeodesic();
var startCartographic = Cesium.Cartographic.fromDegrees(
startLongitude,
startLatitude
);
var redLine;
function addLine () {
redLine = viewer.entities.add({
polyline: {
// This callback updates positions each frame.
positions: new Cesium.CallbackProperty(getEndPoint, false),
width: 5,
material: Cesium.Color.RED,
},
});
addLabel()
viewer.flyTo(redLine)
}
function getEndPoint (time, result) {
endLongitude = startLongitude - 0.001 * Cesium.JulianDate.secondsDifference(time, startTime);
return Cesium.Cartesian3.fromDegreesArray(
[startLongitude, startLatitude, endLongitude, startLatitude],
Cesium.Ellipsoid.WGS84,
result
);
}
// Calculate the length of the line
function getLength (time, result) {
// Get the end position from the polyLine's callback.
var endPoint = redLine.polyline.positions.getValue(time, result)[1];
endCartographic = Cesium.Cartographic.fromCartesian(endPoint);
geodesic.setEndPoints(startCartographic, endCartographic);
var lengthInMeters = Math.round(geodesic.surfaceDistance);
return (lengthInMeters / 1000).toFixed(1) + " km";
}
// Label the polyline with calculated length.
function addLabel () {
var label = viewer.entities.add({
position: new Cesium.CallbackProperty(getMidpoint, isConstant),
label: {
// This callback updates the length to print each frame.
text: new Cesium.CallbackProperty(getLength, isConstant),
font: "20px sans-serif",
pixelOffset: new Cesium.Cartesian2(0.0, 20),
},
});
}
function getMidpoint (time, result) {
// Get the end position from the polyLine's callback.
var endPoint = redLine.polyline.positions.getValue(time, result)[1];
endCartographic = Cesium.Cartographic.fromCartesian(endPoint);
geodesic.setEndPoints(startCartographic, endCartographic);
var midpointCartographic = geodesic.interpolateUsingFraction(
0.5,
scratch
);
return Cesium.Cartesian3.fromRadians(
midpointCartographic.longitude,
midpointCartographic.latitude
);
}
显示结果如下图: