turf.js

Example on how to use turf.js with OpenLayers.

Example showing the integration of turf.js with OpenLayers. The turf.js function along is used to display a marker every 200 meters along a street.

<!DOCTYPE html>
<html>
  <head>
    <title>turf.js</title>
    <link rel="stylesheet" href="https://openlayers.org/en/v4.6.4/css/ol.css" type="text/css">
    <!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
    <script src=""></script>
    <script src="https://openlayers.org/en/v4.6.4/build/ol.js"></script>
    <script src="https://api.tiles.mapbox.com/mapbox.js/plugins/turf/v2.0.0/turf.min.js"></script>
  </head>
  <body>
    <div id="map" class="map"></div>
    <script>
      // this example uses turf.js for which we don't have an externs file.
      var source = new ol.source.Vector();
      fetch('https://openlayers.org/en/v4.6.4/examples/data/geojson/roads-seoul.geojson').then(function(response) {
        return response.json();
      }).then(function(json) {
        var format = new ol.format.GeoJSON();
        var features = format.readFeatures(json);
        var street = features[0];

        // convert to a turf.js feature
        var turfLine = format.writeFeatureObject(street);

        // show a marker every 200 meters
        var distance = 0.2;

        // get the line length in kilometers
        var length = turf.lineDistance(turfLine, 'kilometers');
        for (var i = 1; i <= length / distance; i++) {
          var turfPoint = turf.along(turfLine, i * distance, 'kilometers');

          // convert the generated point to a OpenLayers feature
          var marker = format.readFeature(turfPoint);
          marker.getGeometry().transform('EPSG:4326', 'EPSG:3857');
          source.addFeature(marker);
        }

        street.getGeometry().transform('EPSG:4326', 'EPSG:3857');
        source.addFeature(street);
      });
      var vectorLayer = new ol.layer.Vector({
        source: source
      });

      var rasterLayer = new ol.layer.Tile({
        source: new ol.source.OSM()
      });

      var map = new ol.Map({
        layers: [rasterLayer, vectorLayer],
        target: document.getElementById('map'),
        view: new ol.View({
          center: ol.proj.fromLonLat([126.980366, 37.526540]),
          zoom: 15
        })
      });
    </script>
  </body>
</html>