turf.js Example

Example on how to use turf.js with OpenLayers 3.

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

vector, turfjs, along, distance
<!DOCTYPE html>
<html>
<head>
<title>turf.js Example</title>
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="http://openlayers.org/en/v3.11.2/css/ol.css" type="text/css">
<script src="http://openlayers.org/en/v3.11.2/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 class="container-fluid">

<div class="row-fluid">
  <div class="span12">
    <div id="map" class="map"></div>
  </div>
</div>

</div>
<script>
// NOCOMPILE
// this example uses turf.js for which we don't have an externs file.
var source = new ol.source.Vector();
$.ajax('data/geojson/roads-seoul.geojson').then(function(response) {
  var format = new ol.format.GeoJSON();
  var features = format.readFeatures(response);
  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.MapQuest({
    layer: '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>