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.
import 'ol/ol.css';
import GeoJSON from 'ol/format/GeoJSON';
import Map from 'ol/Map';
import View from 'ol/View';
import {OSM, Vector as VectorSource} from 'ol/source';
import {Tile as TileLayer, Vector as VectorLayer} from 'ol/layer';
import {fromLonLat} from 'ol/proj';
const source = new VectorSource();
fetch('data/geojson/roads-seoul.geojson')
.then(function (response) {
return response.json();
})
.then(function (json) {
const format = new GeoJSON();
const features = format.readFeatures(json);
const street = features[0];
// convert to a turf.js feature
const turfLine = format.writeFeatureObject(street);
// show a marker every 200 meters
const distance = 0.2;
// get the line length in kilometers
const length = turf.lineDistance(turfLine, 'kilometers');
for (let i = 1; i <= length / distance; i++) {
const turfPoint = turf.along(turfLine, i * distance, 'kilometers');
// convert the generated point to a OpenLayers feature
const marker = format.readFeature(turfPoint);
marker.getGeometry().transform('EPSG:4326', 'EPSG:3857');
source.addFeature(marker);
}
street.getGeometry().transform('EPSG:4326', 'EPSG:3857');
source.addFeature(street);
});
const vectorLayer = new VectorLayer({
source: source,
});
const rasterLayer = new TileLayer({
source: new OSM(),
});
const map = new Map({
layers: [rasterLayer, vectorLayer],
target: document.getElementById('map'),
view: new View({
center: fromLonLat([126.980366, 37.52654]),
zoom: 15,
}),
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>turf.js</title>
<!-- Pointer events polyfill for old browsers, see https://caniuse.com/#feat=pointer -->
<script src="https://unpkg.com/elm-pep"></script>
<!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
<script src="https://cdn.polyfill.io/v3/polyfill.min.js?features=fetch,requestAnimationFrame,Element.prototype.classList,URL,TextDecoder,Number.isInteger"></script>
<script src="https://api.tiles.mapbox.com/mapbox.js/plugins/turf/v2.0.0/turf.min.js"></script>
<style>
.map {
width: 100%;
height:400px;
}
</style>
</head>
<body>
<div id="map" class="map"></div>
<script src="main.js"></script>
</body>
</html>
{
"name": "turf",
"dependencies": {
"ol": "6.6.1"
},
"devDependencies": {
"parcel": "^2.0.0-beta.1"
},
"scripts": {
"start": "parcel index.html",
"build": "parcel build --public-url . index.html"
}
}