原文链接及内容

: 本例使用的功能不是稳定API的一部分,可能会在不同版本之间发生变化。请参考API文档以了解最新版本中支持的内容。

运行界面

此示例演示了如何使用WebGLPointsLayer在地图上显示大量的点要素。该图层被赋予了JSON格式的样式,这允许对最终渲染效果(表现、呈现)进行一定程度的定制。可以使用以下运算符:

  • 读取运算符:
    • ['get', 'attributeName']:获取要素属性(着色器中将以a_为前缀)注意:这些属性将从提供给渲染器的属性中获取
    • ['var', 'varName']:从表示样式的变量中获取一个值,如果未定义,则为0
    • ['time']:返回自创建图层以来的时间(以秒为单位)
    • ['zoom']:返回当前的缩放级别
    • ['resolution']:返回当前的分辨率
  • 数学运算符:
    • ['*', value1, value2]:将value1value2相乘
    • ['/', value1, value2]:将value1除以value2
    • ['+', value1, value2]:将value1value2相加
    • ['-', value1, value2]:将value1value2相减
    • ['clamp', value, low, high]:把一个值限制在低值和高值之间
    • ['%', value1, value2]:返回value1%value2(取模)的结果,即余数
    • ['^', value1, value2]:返回value1value2次方
  • 变换运算符:
    • ['case', condition1, output1, ...conditionN, outputN, fallback]:选择其相应条件第一个为真的的计算结果输出。如果未找到匹配项,则返回fallback值。所有条件都应该是布尔值,输出和fallback可以是任何类型。
    • ['match', input, match1, output1, ...matchN, outputN, fallback]:将input值与所有提供的matchX值进行比较,返回与第一个有效匹配项关联的输出值。如果未找到匹配项,则返回fallback值。inputmatchX值必须属于同一类型,并且可以是数字或字符串。outputXfallback值必须属于同一类型,并且可以是任何类型。
    • ['interpolate', interpolation, input, stop1, output1, ...stopN, outputN]:通过在输入和输出对之间进行插值来返回值;插值可以是['linear'](线性)['exponential', base],[“指数”,基数],其中基数是stop Astop B之间的增长率(即插值比率的幂值);值1相当于['linear'][线性]inputstopX值都必须是number类型。outputX值可以是numbercolor。注意:输入将被限制在stop1stopN之间,这意味着所有输出值都将包含在output1outputN之间。
  • 逻辑运算符:
    • ['<', value1, value2]:如果value1严格小于value2,则返回 true,否则返回false
    • ['<=', value1, value2]:如果value1严格小于或等于value2,则返回 true,否则返回false
    • ['>', value1, value2]:如果value1严格大于value2,则返回 true,否则返回false
    • ['>=', value1, value2]:如果value1严格大于或等于value2,则返回 true,否则返回false
    • ['==', value1, value2]:如果value1严格等于value2,则返回 true,否则返回false
    • ['!=', value1, value2]:如果value1不等于value2,则返回 true,否则返回false
    • ['!', value1]:如果value1true或大于0,则返回false,否则返回true
    • ['between', value1, value2, value3]:如果value1包含在value2value3之间(包括在内),则返回 true,否则返回false
  • 转换运算符:
    • ['array', value1, ...valueN]:根据数值创建一个数字数组;请注意,当前值的数量只能是2、3或4。
    • ['color', red, green, blue, alpha]:根据数值创建颜色值;alpha参数是可选的;如果未指定,则将其设置为1。注意:红色、绿色和蓝色分量的值必须介于0和255之间;alpha值介于0和1之间。值可以是字面量(literals),也可以是其他运算符,因为它们将被递归求值。字面值可以是以下类型:
      • 布尔值
      • 数值
      • 字符串

关于字面量(literals)请参见MDN文档:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide/Grammar_and_types#%E5%AD%97%E9%9D%A2%E9%87%8F_literals

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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
import GeoJSON from 'ol/format/GeoJSON.js';
import Map from 'ol/Map.js';
import OSM from 'ol/source/OSM.js';
import TileLayer from 'ol/layer/Tile.js';
import Vector from 'ol/source/Vector.js';
import View from 'ol/View.js';
import WebGLPointsLayer from 'ol/layer/WebGLPoints.js';

const vectorSource = new Vector({
url: 'data/geojson/world-cities.geojson',
format: new GeoJSON(),
wrapX: true,
});

const predefinedStyles = {
'icons': {
symbol: {
symbolType: 'image',
src: 'data/icon.png',
size: [18, 28],
color: 'lightyellow',
rotateWithView: false,
offset: [0, 9],
},
},
'triangles': {
symbol: {
symbolType: 'triangle',
size: 18,
color: [
'interpolate',
['linear'],
['get', 'population'],
20000,
'#5aca5b',
300000,
'#ff6a19',
],
rotateWithView: true,
},
},
'triangles-latitude': {
symbol: {
symbolType: 'triangle',
size: [
'interpolate',
['linear'],
['get', 'population'],
40000,
12,
2000000,
24,
],
color: [
'interpolate',
['linear'],
['get', 'latitude'],
-60,
'#ff14c3',
-20,
'#ff621d',
20,
'#ffed02',
60,
'#00ff67',
],
offset: [0, 0],
opacity: 0.95,
},
},
'circles': {
symbol: {
symbolType: 'circle',
size: [
'interpolate',
['linear'],
['get', 'population'],
40000,
8,
2000000,
28,
],
color: ['match', ['get', 'hover'], 1, '#ff3f3f', '#006688'],
rotateWithView: false,
offset: [0, 0],
opacity: [
'interpolate',
['linear'],
['get', 'population'],
40000,
0.6,
2000000,
0.92,
],
},
},
'circles-zoom': {
symbol: {
symbolType: 'circle',
size: ['interpolate', ['exponential', 2.5], ['zoom'], 2, 1, 14, 32],
color: ['match', ['get', 'hover'], 1, '#ff3f3f', '#006688'],
offset: [0, 0],
opacity: 0.95,
},
},
'rotating-bars': {
symbol: {
symbolType: 'square',
rotation: ['*', ['time'], 0.1],
size: [
'array',
4,
[
'interpolate',
['linear'],
['get', 'population'],
20000,
4,
300000,
28,
],
],
color: [
'interpolate',
['linear'],
['get', 'population'],
20000,
'#ffdc00',
300000,
'#ff5b19',
],
offset: [
'array',
0,
[
'interpolate',
['linear'],
['get', 'population'],
20000,
2,
300000,
14,
],
],
},
},
};

const map = new Map({
layers: [
new TileLayer({
source: new OSM(),
}),
],
target: document.getElementById('map'),
view: new View({
center: [0, 0],
zoom: 2,
}),
});

let literalStyle;
let pointsLayer;

let selected = null;

map.on('pointermove', function (ev) {
if (selected !== null) {
selected.set('hover', 0);
selected = null;
}

map.forEachFeatureAtPixel(ev.pixel, function (feature) {
feature.set('hover', 1);
selected = feature;
return true;
});
});

function refreshLayer(newStyle) {
const previousLayer = pointsLayer;
pointsLayer = new WebGLPointsLayer({
source: vectorSource,
style: newStyle,
});
map.addLayer(pointsLayer);

if (previousLayer) {
map.removeLayer(previousLayer);
previousLayer.dispose();
}
literalStyle = newStyle;
}

const spanValid = document.getElementById('style-valid');
const spanInvalid = document.getElementById('style-invalid');
function setStyleStatus(errorMsg) {
const isError = typeof errorMsg === 'string';
spanValid.style.display = errorMsg === null ? 'initial' : 'none';
spanInvalid.firstElementChild.innerText = isError ? errorMsg : '';
spanInvalid.style.display = isError ? 'initial' : 'none';
}

const editor = document.getElementById('style-editor');
editor.addEventListener('input', function () {
const textStyle = editor.value;
try {
const newLiteralStyle = JSON.parse(textStyle);
if (JSON.stringify(newLiteralStyle) !== JSON.stringify(literalStyle)) {
refreshLayer(newLiteralStyle);
}
setStyleStatus(null);
} catch (e) {
setStyleStatus(e.message);
}
});

const select = document.getElementById('style-select');
select.value = 'circles';
function onSelectChange() {
const style = select.value;
const newLiteralStyle = predefinedStyles[style];
editor.value = JSON.stringify(newLiteralStyle, null, 2);
try {
refreshLayer(newLiteralStyle);
setStyleStatus();
} catch (e) {
setStyleStatus(e.message);
}
}
onSelectChange();
select.addEventListener('change', onSelectChange);

// animate the map
function animate() {
map.render();
window.requestAnimationFrame(animate);
}
animate();

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

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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>WebGL points layer</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>
Choose a predefined style from the list below or edit it as JSON manually.
<select id="style-select">
<option value="icons">Icons</option>
<option value="triangles">Triangles, color related to population</option>
<option value="triangles-latitude">Triangles, color related to latitude</option>
<option value="circles">Circles, size related to population</option>
<option value="circles-zoom">Circles, size related to zoom</option>
<option value="rotating-bars">Rotating bars</option>
</select>
<textarea style="width: 100%; height: 20rem; font-family: monospace; font-size: small;" id="style-editor"></textarea>
<small>
<span id="style-valid" style="display: none; color: forestgreen">✓ style is valid</span>
<span id="style-invalid" style="display: none; color: grey"><span>style not yet valid...</span></span>
&nbsp;
</small>
<!-- 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 type="module" src="main.js"></script>
</body>
</html>