turf.js
turf.js示例。 矢量 turf.js along distance
本示例展示 turf.js 与 OpenLayers 的集成。turf.js 的 along 函数用于沿街道每隔 200 米显示一个标记。
main.js
js
import {along} from '@turf/along';
import {length} from '@turf/length';
import Map from 'ol/Map.js';
import View from 'ol/View.js';
import GeoJSON from 'ol/format/GeoJSON.js';
import TileLayer from 'ol/layer/Tile.js';
import VectorLayer from 'ol/layer/Vector.js';
import {fromLonLat} from 'ol/proj.js';
import OSM from 'ol/source/OSM.js';
import VectorSource from 'ol/source/Vector.js';
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];
// 转换为 turf.js 要素
const turfLine = format.writeFeatureObject(street);
// 每隔 200 米显示一个标记
const distance = 0.2;
// 获取线的长度(单位:千米)
const lineLength = length(turfLine, {units: 'kilometers'});
for (let i = 1; i <= lineLength / distance; i++) {
const turfPoint = along(turfLine, i * distance, {units: 'kilometers'});
// 将生成的点转换为 OpenLayers 要素
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,
}),
});index.html
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>turf.js</title>
<link rel="stylesheet" href="node_modules/ol/ol.css">
<style>
.map {
width: 100%;
height: 400px;
}
</style>
</head>
<body>
<div id="map" class="map"></div>
<script type="module" src="main.js"></script>
</body>
</html>package.json
json
{
"name": "turf",
"dependencies": {
"ol": "10.11.0",
"@turf/along": "^7.1.0",
"@turf/length": "^7.1.0"
},
"devDependencies": {
"vite": "^8.1.5"
},
"scripts": {
"start": "vite",
"build": "vite build"
}
}