Atlaslog
Atlaslog / Examples / MapLibre GL JS / Measure Distances
MapLibre GL JS · Runnable Example

Measure Distances

Runnable MapLibre GL JS example: Measure Distances. 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 MapLibre GL JS examples
/demos/maplibre-measure-distances.htmlLIVE
single HTML file · CDN dependencies onlyinterface may contain Chinese labels

Source

demos/maplibre-measure-distances.html
<!--
  示例:量测距离
  核心逻辑:每次点击追加一个顶点,用 haversine 累加分段距离,再写回线与点的源
  数据:顶点由点击产生,距离在页面内计算
  依赖:MapLibre GL JS 4 · jsDelivr CDN · demotiles 样式
-->
<!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/maplibre-gl@4/dist/maplibre-gl.css">
<style>
  html,body{height:100%;margin:0}
  body{display:flex;flex-direction:column;overflow:hidden;
       font:13px/1.6 -apple-system,"Segoe UI","PingFang SC",sans-serif;color:#16181d}
  .bar{flex:0 0 auto;display:flex;gap:14px;align-items:center;padding:8px 12px;
       background:#f6f7f9;border-bottom:1px solid #e3e6ea;font-size:12px;color:#58606e;flex-wrap:wrap}
  .bar b{color:#16181d;font-weight:600}
  .bar button{background:#fff;border:1px solid #cfd6df;border-radius:4px;padding:3px 10px;
       font:12px/1.4 inherit;color:#3a4250;cursor:pointer}
  .bar button:hover{border-color:#2e86de;color:#2e86de}
  #map{flex:1 1 auto;min-height:0}
</style>
</head>
<body>
<div class="bar">
  <span>顶点 <b id="n">0</b></span>
  <span>总长 <b id="d">0.00 km</b></span>
  <button id="undo">撤销</button>
  <button id="clear">清空</button>
  <span>点击地图逐个落点,距离按球面计算</span>
</div>
<div id="map"></div>
<script src="https://cdn.jsdelivr.net/npm/maplibre-gl@4/dist/maplibre-gl.js"></script>
<script>
(function () {
  'use strict';

  if (typeof maplibregl === 'undefined') {
    document.body.innerHTML =
      '<div style="padding:24px;color:#b42318">MapLibre 加载失败,请检查能否访问 cdn.jsdelivr.net</div>';
    return;
  }

  var R = 6371.0088;
  var RAD = Math.PI / 180;

  function haversine(a, b) {
    var dLat = (b[1] - a[1]) * RAD;
    var dLng = (b[0] - a[0]) * RAD;
    var s = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
      Math.cos(a[1] * RAD) * Math.cos(b[1] * RAD) *
      Math.sin(dLng / 2) * Math.sin(dLng / 2);
    return 2 * R * Math.asin(Math.sqrt(s));
  }

  var pts = [];

  var map = new maplibregl.Map({
    container: 'map',
    style: 'https://demotiles.maplibre.org/style.json',
    center: [108, 34],
    zoom: 3.4,
    attributionControl: { compact: true, customAttribution: 'MapLibre demo tiles' }
  });

  map.addControl(new maplibregl.NavigationControl(), 'top-right');

  var nEl = document.getElementById('n');
  var dEl = document.getElementById('d');

  function emptySource() {
    return { type: 'FeatureCollection', features: [] };
  }

  map.on('load', function () {
    map.addSource('measure-line', { type: 'geojson', data: emptySource() });
    map.addSource('measure-points', { type: 'geojson', data: emptySource() });

    map.addLayer({
      id: 'measure-line',
      type: 'line',
      source: 'measure-line',
      layout: { 'line-cap': 'round', 'line-join': 'round' },
      paint: { 'line-color': '#f03e3e', 'line-width': 2, 'line-dasharray': [3, 2] }
    });

    map.addLayer({
      id: 'measure-points',
      type: 'circle',
      source: 'measure-points',
      paint: {
        'circle-radius': 5,
        'circle-color': '#ffffff',
        'circle-stroke-width': 2.5,
        'circle-stroke-color': '#f03e3e'
      }
    });

    map.addLayer({
      id: 'measure-label',
      type: 'symbol',
      source: 'measure-points',
      layout: {
        'text-field': ['get', 'label'],
        'text-font': ['Noto Sans Regular'],
        'text-size': 12,
        'text-offset': [0, 1.4],
        'text-anchor': 'top'
      },
      paint: {
        'text-color': '#7a2b2b',
        'text-halo-color': '#ffffff',
        'text-halo-width': 1.5
      }
    });
  });

  function total() {
    var sum = 0;
    for (var i = 1; i < pts.length; i++) sum += haversine(pts[i - 1], pts[i]);
    return sum;
  }

  function render() {
    if (!map.getSource('measure-line')) return;

    var sum = 0;
    var features = pts.map(function (p, i) {
      if (i > 0) sum += haversine(pts[i - 1], p);
      return {
        type: 'Feature',
        properties: { label: i === 0 ? '起点' : sum.toFixed(1) + ' km' },
        geometry: { type: 'Point', coordinates: p }
      };
    });

    map.getSource('measure-points').setData({ type: 'FeatureCollection', features: features });
    map.getSource('measure-line').setData({
      type: 'FeatureCollection',
      features: pts.length > 1 ? [{
        type: 'Feature',
        properties: {},
        geometry: { type: 'LineString', coordinates: pts }
      }] : []
    });

    nEl.textContent = pts.length;
    dEl.textContent = total().toFixed(2) + ' km';
  }

  map.on('click', function (e) {
    if (!map.getSource('measure-line')) return;
    pts.push([e.lngLat.lng, e.lngLat.lat]);
    render();
  });

  document.getElementById('undo').addEventListener('click', function () {
    pts.pop();
    render();
  });

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

  map.on('error', function (e) {
    if (e.error) console.warn('地图错误:' + e.error.message);
  });
})();
</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 MapLibre GL JS examples

MapLibre GL JS · EXAMPLEMouse Coordinates MapLibre GL JS · EXAMPLEMulti Map Sync MapLibre GL JS · EXAMPLENon Interactive