Atlaslog
Atlaslog / Examples / Cesium / Measure Distance
Cesium · Runnable Example

Measure Distance

Runnable Cesium example: Measure Distance. Open the live demo, read the complete source, and copy the file into your project. No build step or API key.

Open standalone → Chinese notes All Cesium examples
/demos/cesium-measure-distance.htmlLIVE
single HTML file · CDN dependencies onlyinterface may contain Chinese labels

Source

demos/cesium-measure-distance.html
<!--
  示例:在地球上量测折线距离
  要点:单击取椭球交点,EllipsoidGeodesic.surfaceDistance 累计大圆距离,每段中点标注长度
  依赖:CesiumJS 1.121 · jsDelivr CDN,无外部数据
-->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta name="robots" content="noindex,follow">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>量测距离</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/cesium@1.121.0/Build/Cesium/Widgets/widgets.css">
<style>
  html,body{height:100%;margin:0}
  body{background:#0e1116;color:#e6e8ec;overflow:hidden;
       font:13px/1.6 -apple-system,"Segoe UI","PingFang SC",sans-serif}
  #c{height:100%}
  #c canvas{cursor:crosshair}
  .hud{position:absolute;left:12px;top:12px;z-index:5;background:rgba(23,28,35,.9);
       border:1px solid #2a313b;border-radius:6px;padding:9px 12px;font-size:12px;
       color:#a2a9b6;max-width:262px}
  .hud b{color:#e6e8ec;font-weight:600}
  .hud .row{margin-top:6px}
  .hud .big{font-size:18px;color:#ffb13d;font-family:Consolas,Menlo,monospace}
  .hud button{font:inherit;font-size:12px;padding:3px 9px;border-radius:4px;cursor:pointer;
       border:1px solid #343b46;background:#1d232b;color:#cfd6e2}
  .hud button:hover{background:#262d37}
  .cesium-viewer-bottom .cesium-widget-credits,.cesium-viewer-animationContainer,
  .cesium-viewer-timelineContainer{display:none!important}
</style>
</head>
<body>
<div id="c"></div>
<div class="hud">
  <div><b>距离量测</b></div>
  <div class="row">总距离 <span class="big" id="total">0.00</span> km</div>
  <div class="row">节点 <span id="count">0</span> 个</div>
  <div class="row"><button id="clear">清除全部</button></div>
  <div class="row" style="color:#7f8899">单击加点,右键清空</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/cesium@1.121.0/Build/Cesium/Cesium.js"></script>
<script>
(function () {
  'use strict';

  var viewer = new Cesium.Viewer('c', {
    baseLayer: false,
    baseLayerPicker: false, geocoder: false, homeButton: false,
    sceneModePicker: false, navigationHelpButton: false,
    animation: false, timeline: false, fullscreenButton: false,
    infoBox: false, selectionIndicator: false
  });

  var scene = viewer.scene;
  scene.globe.baseColor = Cesium.Color.fromCssColorString('#1c2733');
  scene.backgroundColor = Cesium.Color.fromCssColorString('#0e1116');
  scene.skyBox.show = false;
  scene.sun.show = false;
  scene.moon.show = false;
  if (scene.skyAtmosphere) scene.skyAtmosphere.show = false;

  var ACCENT = Cesium.Color.fromCssColorString('#ffb13d');
  var points = [];
  var drawn = [];
  var totalEl = document.getElementById('total');
  var countEl = document.getElementById('count');

  function clearDrawn() {
    for (var i = 0; i < drawn.length; i++) viewer.entities.remove(drawn[i]);
    drawn = [];
  }

  function distance(a, b) {
    var geo = new Cesium.EllipsoidGeodesic(
      Cesium.Cartographic.fromCartesian(a),
      Cesium.Cartographic.fromCartesian(b)
    );
    return geo.surfaceDistance;
  }

  function redraw() {
    clearDrawn();
    countEl.textContent = points.length;

    if (points.length === 0) {
      totalEl.textContent = '0.00';
      return;
    }

    var sum = 0;
    for (var i = 1; i < points.length; i++) sum += distance(points[i - 1], points[i]);
    totalEl.textContent = (sum / 1000).toFixed(2);

    for (var p = 0; p < points.length; p++) {
      drawn.push(viewer.entities.add({
        position: points[p],
        point: {
          pixelSize: p === 0 ? 10 : 7,
          color: p === 0 ? Cesium.Color.WHITE : ACCENT,
          outlineColor: ACCENT,
          outlineWidth: 2,
          heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
        }
      }));
    }

    if (points.length > 1) {
      drawn.push(viewer.entities.add({
        polyline: {
          positions: points,
          width: 2,
          clampToGround: true,
          material: ACCENT
        }
      }));

      for (var s = 1; s < points.length; s++) {
        var geo = new Cesium.EllipsoidGeodesic(
          Cesium.Cartographic.fromCartesian(points[s - 1]),
          Cesium.Cartographic.fromCartesian(points[s])
        );
        var mid = geo.interpolateUsingFraction(0.5);
        drawn.push(viewer.entities.add({
          position: Cesium.Cartesian3.fromRadians(mid.longitude, mid.latitude, 0),
          label: {
            text: (geo.surfaceDistance / 1000).toFixed(1) + ' km',
            font: '500 11px Consolas, monospace',
            fillColor: Cesium.Color.WHITE,
            showBackground: true,
            backgroundColor: Cesium.Color.fromCssColorString('#0e1116').withAlpha(0.75),
            backgroundPadding: new Cesium.Cartesian2(6, 3),
            heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
            disableDepthTestDistance: 0
          }
        }));
      }
    }
  }

  var handler = new Cesium.ScreenSpaceEventHandler(scene.canvas);

  handler.setInputAction(function (click) {
    var cartesian = viewer.camera.pickEllipsoid(click.position, scene.globe.ellipsoid);
    if (!Cesium.defined(cartesian)) return;
    var carto = Cesium.Cartographic.fromCartesian(cartesian);
    points.push(Cesium.Cartesian3.fromRadians(carto.longitude, carto.latitude, 0));
    redraw();
  }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

  handler.setInputAction(function () {
    points = [];
    redraw();
  }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);

  document.getElementById('clear').addEventListener('click', function () {
    points = [];
    redraw();
  });

  viewer.camera.flyTo({
    destination: Cesium.Cartesian3.fromDegrees(110, 30, 4200000),
    orientation: { heading: 0, pitch: Cesium.Math.toRadians(-75), roll: 0 },
    duration: 0
  });
})();
</script>
</body>
</html>
Language: the code and this page are in English; the full tutorial and API notes for this example are in Chinese. The demo itself is the authoritative version — it runs exactly as shown.

More Cesium examples

Cesium · EXAMPLEModel Animation Cesium · EXAMPLEModel Distance Cesium · EXAMPLEModel Hpr