原文链接及内容

运行界面

如何在OpenLayers中使用JSTS的示例。

main.js代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import GeoJSON from 'ol/format/GeoJSON.js';
import LinearRing from 'ol/geom/LinearRing.js';
import Map from 'ol/Map.js';
import OSM from 'ol/source/OSM.js';
import VectorSource from 'ol/source/Vector.js';
import View from 'ol/View.js';
import {
LineString,
MultiLineString,
MultiPoint,
MultiPolygon,
Point,
Polygon,
} from 'ol/geom.js';
import {Tile as TileLayer, Vector as VectorLayer} from 'ol/layer.js';
import {fromLonLat} from 'ol/proj.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, {
featureProjection: 'EPSG:3857',
});

const parser = new jsts.io.OL3Parser();
parser.inject(
Point,
LineString,
LinearRing,
Polygon,
MultiPoint,
MultiLineString,
MultiPolygon
);

for (let i = 0; i < features.length; i++) {
const feature = features[i];
// convert the OpenLayers geometry to a JSTS geometry
const jstsGeom = parser.read(feature.getGeometry());

// create a buffer of 40 meters around each line
const buffered = jstsGeom.buffer(40);

// convert back from JSTS and replace the geometry on the feature
feature.setGeometry(parser.write(buffered));
}

source.addFeatures(features);
});
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.979293, 37.528787]),
zoom: 15,
}),
});

界面布局文件index.html代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JSTS Integration</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>
<!-- Pointer events polyfill for old browsers, see https://caniuse.com/#feat=pointer -->
<script src="https://cdn.jsdelivr.net/npm/elm-pep@1.0.6/dist/elm-pep.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jsts@2.3.0/dist/jsts.min.js"></script>
<script type="module" src="main.js"></script>
</body>
</html>