样式表达式
样式表达式示例。 矢量 样式 expression
要以相同的方式样式化图层中的所有要素,可以使用带字面值的符号化(symbolizer)对象,如下方陆地(land)图层所示。在这种情况下,所有要素具有相同的填充颜色。 要根据要素属性对图层中的要素进行样式化,可以在符号化对象中提供表达式来代替字面值。在下方第一个居民地图层中,圆的半径基于 scalerank 属性。 要根据要素属性有条件地应用不同的符号化对象,可以提供一组规则。每条规则都可以包含一个 filter 表达式。如果该表达式求值为 true,则应用该规则的 style。带有 else: true 的规则会在前面所有规则都不适用时生效。居民地标注是通过提供给第三个图层的一组规则来渲染的。
main.js
js
import Map from 'ol/Map.js';
import View from 'ol/View.js';
import GeoJSON from 'ol/format/GeoJSON.js';
import Layer from 'ol/layer/Vector.js';
import Source from 'ol/source/Vector.js';
const format = new GeoJSON();
const map = new Map({
layers: [
new Layer({
background: '#1a2b39',
source: new Source({
url: 'https://d2ad6b4ur7yvpq.cloudfront.net/naturalearth-3.3.0/ne_110m_land.geojson',
format,
}),
style: {
'fill-color': 'darkgray',
},
}),
new Layer({
source: new Source({
url: 'https://d2ad6b4ur7yvpq.cloudfront.net/naturalearth-3.3.0/ne_50m_populated_places_simple.geojson',
format,
}),
style: {
'circle-radius': ['get', 'scalerank'],
'circle-fill-color': 'gray',
'circle-stroke-color': 'white',
'circle-stroke-width': 0.5,
},
}),
new Layer({
source: new Source({
url: 'https://d2ad6b4ur7yvpq.cloudfront.net/naturalearth-3.3.0/ne_50m_populated_places_simple.geojson',
format,
}),
declutter: true,
style: [
{
filter: ['>', ['get', 'pop_max'], 10_000_000],
style: {
'text-value': [
'concat',
['get', 'adm1name'],
', ',
['get', 'adm0name'],
],
'text-font': '16px sans-serif',
'text-fill-color': 'white',
'text-stroke-color': 'gray',
'text-stroke-width': 2,
},
},
{
else: true,
filter: ['>', ['get', 'pop_max'], 5_000_000],
style: {
'text-value': ['get', 'nameascii'],
'text-font': '12px sans-serif',
'text-fill-color': 'white',
'text-stroke-color': 'gray',
'text-stroke-width': 2,
},
},
],
}),
],
target: 'map',
view: new View({
center: [0, 0],
zoom: 1,
}),
});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": "style-expressions",
"dependencies": {
"ol": "10.11.0"
},
"devDependencies": {
"vite": "^8.1.5"
},
"scripts": {
"start": "vite",
"build": "vite build"
}
}