原文链接及内容

运行界面

为了以相同的方式设置图层中所有要素的样式,你可以为上述的土地图层使用具有字面值的符号器对象。在这种情况下,所有的要素将具有相同的填充颜色。但为了根据要素属性设置图层中的要素样式,可以在符号器中提供表达式而不是字面值。在上述第一个图层——居住地图层,圆的半径是基于scalerank属性。为了根据要素属性应用不同的符号,可以提供一系列的规则,而每个规则都可以有一个filter表达式,如果此表达式的计算结果为真,这条规则的style则会被应用。若之前的规则都没被应用,则会应用有else: true的规则。居住地标签则会被一系列的规则渲染于第三个图层。

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 Layer from 'ol/layer/Vector.js';
import Map from 'ol/Map.js';
import Source from 'ol/source/Vector.js';
import View from 'ol/View.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': ['get', 'nameascii'],
'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代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Style Expressions</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>