Cesium JS Line Length
You could use Cesium.EllipsoidGeodesic#surfaceDistance
to calculate the distance in meters, and then convert to kilometers.
var startCartesian3Point = Cesium.Cartesian3.fromDegrees(48.862165, 2.305189);
var endCartesian3Point = Cesium.Cartesian3.fromDegrees(45.755675, 4.822185);
var startCartographicPoint = Cesium.Cartographic.fromCartesian(startCartesian3Point);
var endCartographicPoint = Cesium.Cartographic.fromCartesian(endCartesian3Point);
var ellipsoidGeodesic = new Cesium.EllipsoidGeodesic(startCartographicPoint,
endCartographicPoint );
var distance = ellipsoidGeodesic.surfaceDistance;
var distanceInKm = distance * 0.001;
console.log('Geodesic distance: ' + distanceInKm + ' Km');
So, there is a Cartesian3.distance function, however, the answer here is not as simple as just calling this on all the pairs of points in positions
.
The problem is the line in your example has significant Earth curvature showing, and simply calling distance
will get a straight-line geometric distance, cutting through the Earth's crust to get where it's going. Clearly the line showing on the Cesium globe doesn't do this, so, we need to reach into the guts of Cesium a bit to get all the intermediate points along this line. These intermediate points add to the polyline's total length by following the curvature of the Earth's surface.
But first, extract a variable for your positions:
var positions = Cesium.Cartesian3.fromDegreesArray([
-104.606667,50.454722,
15.71666666, 69.1 ]);
(or, alternately, var positions = orangeOutlined.polyline.positions.getValue();
which is the same thing in this case)
Next, call PolylinePipeline.generateArc
to generate the intermediate points from these positions. Note this whole class is marked @private
which means the API is subject to change between versions without notice, but there's no other way to get to this helper function.
var surfacePositions = Cesium.PolylinePipeline.generateArc({
positions: positions
});
The return value here is a flat array of raw Cartesian values, not Cartesian3
objects. We sum up the distances between adjacent pairs, like so:
var scratchCartesian3 = new Cesium.Cartesian3();
var surfacePositionsLength = surfacePositions.length;
var totalDistanceInMeters = 0;
for (var i = 3; i < surfacePositionsLength; i += 3) {
scratchCartesian3.x = surfacePositions[i] - surfacePositions[i - 3];
scratchCartesian3.y = surfacePositions[i + 1] - surfacePositions[i - 2];
scratchCartesian3.z = surfacePositions[i + 2] - surfacePositions[i - 1];
totalDistanceInMeters += Cesium.Cartesian3.magnitude(scratchCartesian3);
}
Finally, we can display the distance.
var totalDistanceInKm = totalDistanceInMeters * 0.001;
console.log('Distance: ' + totalDistanceInKm + ' km');
For this sample line, I get a reported distance of 5881.7 km. The Google Maps measure tool reports 5,862 km for a similar measurement, so this seems like a good sanity check that the method described here works.