Getting the height at mouse location

Hi,
I am trying to figure out how to get the height on mouse click (above sea level).
Preferabbly, I would like to get the heightmap from GeoServer, though corrently I’m simply using the default cesium maps.

I couldn’t find any posts which suit my needs.

In the following function I get the position of the mouse click, convert it to lng/lat, and then attempt to use the Cesium.sampleTerrainMostDetailed. But the height I get back is always zero.

I’ll also note that I initiated the TerrainProvider with maptiler’s free provider (Free Terrain Tiles for Cesium | MapTiler).

Blockquote
function onMouseLeftClick(position: Cartesian2){
console.log(“Left Click Position:”, position);
if(!viewerRef.current || !viewerRef.current.cesiumElement){
return;
//get height
const viewer = viewerRef.current.cesiumElement;
const cartographicPosition = convertScreenPixelToLocation(position)
if(!cartographicPosition){
return;
}
const cartographic = new Cesium.Cartographic(cartographicPosition.lng, cartographicPosition.lat);
Cesium.sampleTerrainMostDetailed(viewer.terrainProvider, [cartographic]).then(function(terrainData) {
console.log(“Terrain Data :”, terrainData[0]);
})

Thank you

Hi,
You can simply do something like this:

const viewer = new Cesium.Viewer("cesiumContainer", {
  terrainProvider: Cesium.createWorldTerrain(),
});

var handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
handler.setInputAction(function (event) {
  var ray = viewer.camera.getPickRay(event.endPosition);
    var mousePosition = viewer.scene.globe.pick(ray, viewer.scene);
    if (Cesium.defined(mousePosition)) {
        var cartographic = Cesium.Cartographic.fromCartesian(mousePosition);
        var latitudeString = Cesium.Math.toDegrees(cartographic.latitude).toFixed(3);
        var longitudeString = Cesium.Math.toDegrees(cartographic.longitude).toFixed(3);
        var heightString = cartographic.height.toFixed(2);
        var lhtext =
            `Lat: ${(latitudeString).slice(-8)}, Lon: ${(longitudeString).slice(-8)}, Alt: ${(heightString).slice(-7)}`;

        console.log(lhtext);
    }
}, Cesium.ScreenSpaceEventType.MOUSE_MOVE);