自定义多边形样式
自定义多边形样式示例。 多边形 矢量 样式 GeometryFunction
本示例为多边形创建了两种不同的样式:
第一种样式用于多边形本身。
第二种样式用于绘制多边形的顶点。
main.js
js
import Map from 'ol/Map.js';
import View from 'ol/View.js';
import GeoJSON from 'ol/format/GeoJSON.js';
import MultiPoint from 'ol/geom/MultiPoint.js';
import VectorLayer from 'ol/layer/Vector.js';
import VectorSource from 'ol/source/Vector.js';
import CircleStyle from 'ol/style/Circle.js';
import Fill from 'ol/style/Fill.js';
import Stroke from 'ol/style/Stroke.js';
import Style from 'ol/style/Style.js';
const styles = [
/* 我们为多边形使用了两种不同的样式:
* - 第一种样式用于多边形本身。
* - 第二种样式用于绘制多边形的顶点。
* 在自定义的 `geometry` 函数中,多边形的顶点会作为
* `MultiPoint` 几何对象返回,用于渲染该样式。
*/
new Style({
stroke: new Stroke({
color: 'blue',
width: 3,
}),
fill: new Fill({
color: 'rgba(0, 0, 255, 0.1)',
}),
}),
new Style({
image: new CircleStyle({
radius: 5,
fill: new Fill({
color: 'orange',
}),
}),
geometry: function (feature) {
// 返回多边形第一个环的坐标
const coordinates = feature.getGeometry().getCoordinates()[0];
return new MultiPoint(coordinates);
},
}),
];
const geojsonObject = {
'type': 'FeatureCollection',
'features': [
{
'type': 'Feature',
'geometry': {
'type': 'Polygon',
'coordinates': [
[
[-5e6, 6e6],
[-5e6, 8e6],
[-3e6, 8e6],
[-3e6, 6e6],
[-5e6, 6e6],
],
],
},
},
{
'type': 'Feature',
'geometry': {
'type': 'Polygon',
'coordinates': [
[
[-2e6, 6e6],
[-2e6, 8e6],
[0, 8e6],
[0, 6e6],
[-2e6, 6e6],
],
],
},
},
{
'type': 'Feature',
'geometry': {
'type': 'Polygon',
'coordinates': [
[
[1e6, 6e6],
[1e6, 8e6],
[3e6, 8e6],
[3e6, 6e6],
[1e6, 6e6],
],
],
},
},
{
'type': 'Feature',
'geometry': {
'type': 'Polygon',
'coordinates': [
[
[-2e6, -1e6],
[-1e6, 1e6],
[0, -1e6],
[-2e6, -1e6],
],
],
},
},
],
};
const source = new VectorSource({
features: new GeoJSON().readFeatures(geojsonObject),
});
const layer = new VectorLayer({
source: source,
style: styles,
});
const map = new Map({
layers: [layer],
target: 'map',
view: new View({
center: [0, 3000000],
zoom: 2,
}),
});index.html
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>自定义多边形样式</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": "polygon-styles",
"dependencies": {
"ol": "10.11.0"
},
"devDependencies": {
"vite": "^8.1.5"
},
"scripts": {
"start": "vite",
"build": "vite build"
}
}