Atlaslog
Atlaslog / Examples / Turf.js / Length
Turf.js · Runnable Example

Length

Runnable Turf.js example: Length. 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 Turf.js examples
/demos/turf-length.htmlLIVE
single HTML file · CDN dependencies onlyinterface may contain Chinese labels

Source

demos/turf-length.html
<!--
  示例:计算长度 — 对多段路线用 turf.length 求总里程,逐段用 distance 拆分
  核心逻辑:总线长与每段长度分开输出,避免把拐点数量当成里程
  依赖:Turf.js 7 · 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>
<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;background:#fff}
  .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}
  svg{flex:1 1 auto;min-height:0;width:100%;display:block;background:#fbfcfd}
  .out{flex:0 0 auto;display:flex;gap:22px;flex-wrap:wrap;padding:8px 12px;
       border-top:1px solid #e3e6ea;
       font-family:ui-monospace,Consolas,monospace;font-size:11.5px;color:#3a4250}
  .out b{color:#1f5fd0}
  .out span.seg{color:#58606e}
</style>
</head>
<body>
<div class="bar">
  <span>总里程 <b id="total">—</b></span>
  <span>段数 <span id="n">—</span></span>
</div>
<svg id="stage" viewBox="0 0 640 320" preserveAspectRatio="xMidYMid meet"></svg>
<div class="out" id="segs"></div>
<script src="https://cdn.jsdelivr.net/npm/@turf/turf@7/turf.min.js"></script>
<script>
(function () {
  'use strict';

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

  var coords = [
    [116.300, 39.880],
    [116.352, 39.896],
    [116.402, 39.918],
    [116.470, 39.905],
    [116.520, 39.940]
  ];

  var route = turf.lineString(coords, { name: '巡查路线' });
  var W = 640, H = 320, PAD = 40;
  var stage = document.getElementById('stage');
  var bbox = turf.bbox(route);

  var kx = Math.cos(((bbox[1] + bbox[3]) / 2) * Math.PI / 180);
  var x0 = bbox[0] * kx, x1 = bbox[2] * kx;
  var y0 = bbox[1], y1 = bbox[3];
  var s = Math.min((W - PAD * 2) / (x1 - x0), (H - PAD * 2) / (y1 - y0));
  var ox = (W - (x1 - x0) * s) / 2;
  var oy = (H - (y1 - y0) * s) / 2;

  function pr(c) {
    return [(c[0] * kx - x0) * s + ox, (y1 - c[1]) * s + oy];
  }

  var parts = ['<rect x="0" y="0" width="640" height="320" fill="none" stroke="#e3e6ea"/>'];
  var d = '';
  coords.forEach(function (c, i) {
    var p = pr(c);
    d += (i ? 'L' : 'M') + p[0].toFixed(1) + ' ' + p[1].toFixed(1);
  });

  parts.push('<path d="' + d + '" fill="none" stroke="#1f5fd0" stroke-width="5" ' +
             'stroke-linecap="round" stroke-linejoin="round" opacity="0.25"/>');
  parts.push('<path d="' + d + '" fill="none" stroke="#1f5fd0" stroke-width="2" ' +
             'stroke-linecap="round" stroke-linejoin="round"/>');

  var segLengths = [];
  for (var i = 1; i < coords.length; i++) {
    var seg = turf.distance(turf.point(coords[i - 1]), turf.point(coords[i]),
                            { units: 'kilometers' });
    segLengths.push(seg);

    var a = pr(coords[i - 1]), b = pr(coords[i]);
    var mx = (a[0] + b[0]) / 2, my = (a[1] + b[1]) / 2;

    parts.push('<text x="' + mx.toFixed(1) + '" y="' + (my - 6).toFixed(1) +
               '" font-size="11" text-anchor="middle" fill="#58606e">' +
               seg.toFixed(2) + '</text>');
  }

  coords.forEach(function (c, i) {
    var p = pr(c);
    parts.push('<circle cx="' + p[0].toFixed(1) + '" cy="' + p[1].toFixed(1) +
               '" r="4.5" fill="#fff" stroke="#1f5fd0" stroke-width="2"/>');
    parts.push('<text x="' + (p[0] + 8).toFixed(1) + '" y="' + (p[1] + 4).toFixed(1) +
               '" font-size="11" fill="#1f5fd0">P' + (i + 1) + '</text>');
  });

  stage.innerHTML = parts.join('');

  var total = turf.length(route, { units: 'kilometers' });
  document.getElementById('total').textContent = total.toFixed(2) + ' km';
  document.getElementById('n').textContent = segLengths.length;

  document.getElementById('segs').innerHTML = segLengths.map(function (v, i) {
    return '<span class="seg">P' + (i + 1) + ' → P' + (i + 2) + ' <b>' +
           v.toFixed(3) + ' km</b></span>';
  }).join('');
})();
</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 Turf.js examples

Turf.js · EXAMPLELine Chunk Turf.js · EXAMPLELine Slice Turf.js · EXAMPLEMask