Atlaslog
Atlaslog / Examples / OpenLayers / Turf
OpenLayers · Runnable Example

Turf

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

Source

demos/openlayers-turf.html
<!--
  示例:OpenLayers 沿线等距采点
  要点:页面内实现 haversine 长度与沿线插值,替代 @turf/along 与 @turf/length
  依赖:OpenLayers 10.3.1 · 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/ol@10.3.1/ol.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}
  .bar{flex:0 0 auto;padding:8px 12px;background:#f6f7f9;border-bottom:1px solid #e3e6ea;
       display:flex;gap:10px;align-items:center;flex-wrap:wrap;font-size:12px;color:#58606e}
  .bar label{display:flex;gap:5px;align-items:center;cursor:pointer}
  .bar select,.bar input[type=range]{font-size:12px}
  .bar .val{font-family:ui-monospace,Consolas,monospace;color:#1f5fd0;min-width:44px}
  .bar .sep{width:1px;height:16px;background:#d8dce2}
  #map{flex:1 1 auto;min-height:0;background:#eef0f3}
</style>
</head>
<body>
<div class="bar">
  <span>采样间隔 200 m</span>
  <span class="sep"></span>
  <span id="info">计算中…</span>
</div>
<div id="map"></div>
<script src="https://cdn.jsdelivr.net/npm/ol@10.3.1/dist/ol.js"></script>
<script>
(function () {
  'use strict';

  if (typeof ol === 'undefined') {
    document.getElementById('map').textContent = 'OpenLayers 加载失败,请检查能否访问 cdn.jsdelivr.net';
    return;
  }


  function haversine(a, b) {
    var radius = 6371008.8;
    var toRad = Math.PI / 180;
    var dLat = (b[1] - a[1]) * toRad;
    var dLon = (b[0] - a[0]) * toRad;
    var lat1 = a[1] * toRad;
    var lat2 = b[1] * toRad;
    var h = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
      Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2);
    return 2 * radius * Math.asin(Math.min(1, Math.sqrt(h)));
  }

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

  function along(coords, distance) {
    var travelled = 0;
    for (var i = 1; i < coords.length; ++i) {
      var segment = haversine(coords[i - 1], coords[i]);
      if (travelled + segment >= distance) {
        var t = (distance - travelled) / segment;
        return [
          coords[i - 1][0] + (coords[i][0] - coords[i - 1][0]) * t,
          coords[i - 1][1] + (coords[i][1] - coords[i - 1][1]) * t
        ];
      }
      travelled += segment;
    }
    return coords[coords.length - 1].slice();
  }

  var road = [
    [116.350, 39.890],
    [116.365, 39.898],
    [116.380, 39.900],
    [116.392, 39.909],
    [116.405, 39.916],
    [116.420, 39.922],
    [116.438, 39.928],
    [116.452, 39.936]
  ];

  var total = lineLength(road);
  var step = 0.2;

  var lineFeature = new ol.Feature({
    geometry: new ol.geom.LineString(road.map(function (p) {
      return ol.proj.fromLonLat(p);
    }))
  });

  var markers = [];
  for (var d = step; d <= total / 1000; d += step) {
    var point = along(road, d * 1000);
    markers.push(new ol.Feature({
      geometry: new ol.geom.Point(ol.proj.fromLonLat(point)),
      distance: d
    }));
  }

  var vectorSource = new ol.source.Vector({
    features: [lineFeature].concat(markers)
  });

  var vector = new ol.layer.Vector({
    source: vectorSource,
    style: function (feature) {
      if (feature.getGeometry() instanceof ol.geom.LineString) {
        return new ol.style.Style({
          stroke: new ol.style.Stroke({color: '#1f5fd0', width: 3})
        });
      }
      return new ol.style.Style({
        image: new ol.style.Circle({
          radius: 5,
          fill: new ol.style.Fill({color: '#ff8f00'}),
          stroke: new ol.style.Stroke({color: '#ffffff', width: 2})
        })
      });
    }
  });

  var map = new ol.Map({
    target: 'map',
    layers: [
      new ol.layer.Tile({source: new ol.source.XYZ({url: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}', attributions: 'Tiles © Esri'})}),
      vector
    ],
    view: new ol.View({
      center: ol.proj.fromLonLat([116.400, 39.912]),
      zoom: 13
    })
  });

  map.getView().fit(vectorSource.getExtent(), {padding: [70, 70, 70, 70]});

  document.getElementById('info').textContent =
    '全长 ' + (total / 1000).toFixed(2) + ' km · 采样 ' + markers.length + ' 个点';

})();
</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 OpenLayers examples

OpenLayers · EXAMPLETwo Finger Pan Scroll OpenLayers · EXAMPLEUtfgrid OpenLayers · EXAMPLEVector Esri