Openlayers3根据Zoom切换图层

最近想用 Openlayers3 根据 Zoom 的级别,从而切换不同的图层,查询了相关资料和在同事的帮助下完成了如下的效果:

实现代码如下:

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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Gis展示</title>
<link rel="stylesheet" href="jslib/openlayer3/css/ol.css" type="text/css">
<script src="jslib/openlayer3/build/ol.js"></script>
<script src="jslib/jquery.min.js"></script>
<script src="jslib/Gis.js"></script>
</head>
<body>
<div id="map" class="map"></div>
<script>
var country = '第一图层请求地址';
var province = '第二图层请求地址';
var city = '第三图层请求地址';

var layerCount = 2;
var map = Gis().map();
var view = map.getView();
Gis().saveOnlyLayer(map,'China');
map.addLayer(Gis().createGeoLayer(country,'country'));
/*
默认加载全国图层,当处于处于全国区域,加载省份图层,将其隐藏
当处于省份图层加载城市图层,将其隐藏,从而提高价值速度
*/
view.on('change:resolution',function(event){
var zLevel = view.getZoom();
// event
if (zLevel <= '5') {
if (layerCount >= 0 )
{
Gis().addMapLayer(Gis().createGeoLayer(province,'province'),'province');
}
layerCount -= 1;
Gis().viewLayer(map, 'country');
}
else if (zLevel <= '7') {
if (layerCount >= 0 ) {
Gis().addMapLayer(Gis().createGeoLayer(city,'city'),'city');
}
layerCount -= 1;
Gis().viewLayer(map, 'province');
} else{
Gis().viewLayer(map, 'city');
}
console.log(zLevel);
});
</script>
</body>
</html>

关于图层切换提高其加载速度和效率,初始情况下加载第一图层,在 Zoom 属于第一图层的级别中,加载第二图层数据并将其隐藏,同理在 Zoom 属于第二图层的级别中,加载第三图层数据并隐藏,通过 layerCount 变量确保三个图层数据加载请求一次,三个图层加载完成,只有通过 layer 的 setVisible 方法实现图层的显示.其中 Gis.js 文件是自己封装的关于 Openlayers3 的常见操作.

完整代码如下:

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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
var Gis = function() {
//坐标系
var deproj = ol.proj.get('EPSG:4326');
//中心坐标
var coordinates = [113.653055, 34.800358];
//矢量层数据源
var vectorSource = 'gisData.json';
//默认的style
var image = new ol.style.Circle({
radius: 5,
fill: new ol.style.Fill({
color: 'red'
}),
stroke: new ol.style.Stroke({color: 'red', width: 1})
});
var styles = {
'Point': new ol.style.Style({
image: image
}),
'LineString': new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'green',
width: 1
})
}),
'MultiLineString': new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'green',
width: 1
})
}),
'MultiPoint': new ol.style.Style({
image: image
}),
'MultiPolygon': new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'green',
width: 1
}),
fill: new ol.style.Fill({
color: 'rgba(255, 255, 0, 0.1)'
})
}),
'Polygon': new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'green',
lineDash: [4],
width: 3
}),
fill: new ol.style.Fill({
color: 'rgba(0, 0, 255, 0.1)'
})
}),
'GeometryCollection': new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'magenta',
width: 2
}),
fill: new ol.style.Fill({
color: 'magenta'
}),
image: new ol.style.Circle({
radius: 10,
fill: null,
stroke: new ol.style.Stroke({
color: 'magenta'
})
})
}),
'Circle': new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'red',
width: 2
}),
fill: new ol.style.Fill({
color: 'rgba(255,0,0,0.2)'
})
})
};

var maxvalue = 4;
var minvalue = 0;
var changeStyles = {
'Point': new ol.style.Style({
image: image
}),
'LineString': new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'green',
width: 1
})
}),
'MultiLineString': new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'green',
width: 1
})
}),
'MultiPoint': new ol.style.Style({
image: image
}),
'MultiPolygon': new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'yellow',
width: 1
}),
fill: new ol.style.Fill({
color: 'rgba(255, 255, 0, 0.1)'
})
}),
'Polygon': new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'blue',
lineDash: [4],
width: 3
}),
fill: new ol.style.Fill({
color: 'rgba(0, 0, 255, 0.1)'
})
}),
'GeometryCollection': new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'magenta',
width: 2
}),
fill: new ol.style.Fill({
color: 'magenta'
}),
image: new ol.style.Circle({
radius: 10,
fill: null,
stroke: new ol.style.Stroke({
color: 'magenta'
})
})
}),
'Circle': new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'red',
width: 2
}),
fill: new ol.style.Fill({
color: 'rgba(255,0,0,0.2)'
})
})
};
function getColorByLevel(level) {
// console.log(level+"int"+parseInt(level));
if(parseInt(level) == 1){
return '#cc0000';
}
if(parseInt(level) == 2){
return '#ff9900';
}
if(parseInt(level) == 4){
return '#8dc43c';
}
if(parseInt(level) == 3){
return '#b6d7a8';
}
return '#ffffff';
}
function getColorByPercentValue(value) {
// console.log(value);
if(parseFloat(value) >= 0.3 && parseFloat(value) <= 1){
return '#cc0000';
}
if(parseFloat(value) >= 0.2 && parseFloat(value) < 0.3){
return '#ff9900';
}
if(parseFloat(value) >= 0.1 && parseFloat(value) < 0.2){
return '#b6d7a8';
}
if(parseFloat(value) >= 0 && parseFloat(value) < 0.1){
return '#8dc43c';
}
return '#ffffff';
}
function getColorByDensityValue(value) {
// console.log(value);
if(value == 'A' || value == '1'){
return '#cc0000';
}
if(value == 'B' || value == '2'){
return '#ff9900';
}
if(value == 'C' || value == '3'){
return '#b6d7a8';
}
if(value == 'D' || value == '4'){
return '#8dc43c';
}
return '#ffffff';
}
//获取宫格的填充样式,根据宫格ID获取宫格对应的指标值,然后进行插值
function getFillStyle(feature) {
var gridvalue = feature.getProperties().value;
var color = getColorByLevel(gridvalue);
// console.log(color);
var styleArray = [new ol.style.Style({
fill: new ol.style.Fill({
color: color
}),
stroke: new ol.style.Stroke({
color: '#000000',
width: 1
})
})];
return styleArray;
}
function getNetFillStyle(feature){
var gridvalue = feature.getProperties().value;
var color = getColorByPercentValue(gridvalue);
// console.log(color);
var styleArray = [new ol.style.Style({
fill: new ol.style.Fill({
color: color
}),
stroke: new ol.style.Stroke({
color: '#000000',
width: 1
})
})];
return styleArray;
}
function getDensityFillStyle(feature){
var gridvalue = feature.getProperties().value;
console.log(gridvalue);
var color = getColorByDensityValue(gridvalue);
var styleArray = [new ol.style.Style({
fill: new ol.style.Fill({
color: color
}),
stroke: new ol.style.Stroke({
color: '#000000',
width: 1
})
})];
return styleArray;
}
/**
* 设置默认投影系
*
* @param proj 新的投影系
*/
function setDeproj(proj) {
deproj = ol.proj.get(proj);
}
/**
* 设置地图中心点坐标
*
* @param coord[Array] 中心点坐标
*/
function setCoordinates(coord) {
coordinates = [coord[0],coord[1]];
}
/**
* 设置矢量图层数据源
*
* @param source[string] 矢量图层来源
*/
function setVectorLayerSource(source) {
vectorSource = source;
}
/**
* 设置显示的样式
*
* @param style 样式
*/
function setStyle(style) {
styles = style;
}
/**
* 根据不同feature按照不同样式显示
*
* @param feature 坐标数据
*/
function styleFunction(feature) {
// console.log(feature.getGeometry().getType());
return styles[feature.getGeometry().getType()];
}
function cstyleFunction(feature) {
//console.log(feature.getGeometry().getType());
return styles[feature.getGeometry().getType()];
}
/**
* 获得矢量图层
*
* @param title 根据title创建指定图层
*
* @return Object 矢量层对象
*/
function getGeoLayer(title) {
var GeoJsonLayer = new ol.layer.Vector({
title: title,
source: new ol.source.Vector({
url: vectorSource,
format: new ol.format.GeoJSON()
}),
style: styleFunction
});
return GeoJsonLayer;
}

function getKmlLayer(title) {
var KMLLayer = new ol.layer.Vector({
title: title,
source: new ol.source.Vector({
url: vectorSource,
format: new ol.format.KML()
}),
style: styleFunction
});
return KMLLayer;
}

function createGeoLayer(source, title) {
if (typeof(source) == 'object') {
console.log("readFeatures");
var vectorSource = new ol.source.Vector({
features: (new ol.format.GeoJSON()).readFeatures(source)
});
var GeoJsonLayer = new ol.layer.Vector({
title: title,
source: vectorSource,
updateWhileInteracting: true,
style: styleFunction
});
} else {
console.log("sourceUrl");
var GeoJsonLayer = new ol.layer.Vector({
title: title,
source: new ol.source.Vector({
url: source,
format: new ol.format.GeoJSON()
}),
updateWhileInteracting: true,
style: styleFunction
});
}
return GeoJsonLayer;
}

function createKMLLayer(sourceUrl, title) {
var GeoJsonLayer = new ol.layer.Vector({
title: title,
source: new ol.source.Vector({
url: sourceUrl,
format: new ol.format.KML({
extractStyles: false
})
}),
// updateWhileInteracting: true,
style: cstyleFunction
});
console.log("createKMLLayer");
return GeoJsonLayer;
}
function createGridGeoLayer(source, title) {
if (typeof(source) == 'object') {
console.log("readFeatures");
var vectorSource = new ol.source.Vector({
features: (new ol.format.GeoJSON()).readFeatures(source)
});
var GeoJsonLayer = new ol.layer.Vector({
title: title,
source: vectorSource,
updateWhileInteracting: true,
style: function(feature, resolution) {
return getFillStyle(feature);
}
});
} else {
console.log("sourceUrl");
var GeoJsonLayer = new ol.layer.Vector({
title: title,
source: new ol.source.Vector({
url: source,
format: new ol.format.GeoJSON()
}),
updateWhileInteracting: true,
style: function(feature, resolution) {
return getFillStyle(feature);
}
});
}
return GeoJsonLayer;
}
function createPercentGeoLayer(source, title){
if (typeof(source) == 'object') {
console.log("readFeatures");
var vectorSource = new ol.source.Vector({
features: (new ol.format.GeoJSON()).readFeatures(source)
});
var GeoJsonLayer = new ol.layer.Vector({
title: title,
source: vectorSource,
updateWhileInteracting: true,
style: function(feature, resolution) {
return getNetFillStyle(feature);
}
});
} else {
console.log("sourceUrl");
var GeoJsonLayer = new ol.layer.Vector({
title: title,
source: new ol.source.Vector({
url: source,
format: new ol.format.GeoJSON()
}),
updateWhileInteracting: true,
style: function(feature, resolution) {
return getNetFillStyle(feature);
}
});
}
return GeoJsonLayer;
}
function createDensityGeoLayer(source, title){
if (typeof(source) == 'object') {
console.log("readFeatures");
var vectorSource = new ol.source.Vector({
features: (new ol.format.GeoJSON()).readFeatures(source)
});
var GeoJsonLayer = new ol.layer.Vector({
title: title,
source: vectorSource,
updateWhileInteracting: true,
style: function(feature, resolution) {
return getDensityFillStyle(feature);
}
});
} else {
console.log("sourceUrl");
var GeoJsonLayer = new ol.layer.Vector({
title: title,
source: new ol.source.Vector({
url: source,
format: new ol.format.GeoJSON()
}),
updateWhileInteracting: true,
style: function(feature, resolution) {
return getDensityFillStyle(feature);
}
});
}
return GeoJsonLayer;
}
/**
* 根据文件名称获取文件后缀名
*
* @param filename 文件名
*
* @return string 后缀名
*/
function getFileExtension(filenaem) {
var result = /\.[^\.]+/.exec(filenaem);
return result;
}
/**
* 获取地图信息
*
* @return Object map对象
*/
function getMap() {
if (arguments.length === 1) {
setVectorLayerSource(arguments[0]);
}
if (getFileExtension(arguments[0]) == 'json') {
var vectorLayer = getGeoLayer();
} else if (getFileExtension(arguments[0]) == 'kml') {
var vectorLayer = getKmlLayer();
} else {
var vectorLayer = new ol.layer.Vector({
title: 'station Layer',
source: new ol.source.Vector({
format: new ol.format.KML()
}),
style: styleFunction
});
}
var map = new ol.Map({
layers: [
new ol.layer.Tile({
title: 'China',
source: new ol.source.OSM()
}),
vectorLayer
],
target: 'map',
controls: ol.control.defaults({
attributionOptions: /** @type {olx.control.AttributionOptions} */ ({
collapsible: false
})
}),
view: new ol.View({
projection: deproj,
center: coordinates,
zoom: 4,
maxZoom: 16,
minZoom: 4
})
});
return map;
}
/**
* 保留指定图层,移除其他图层
*
* @param map 地图对象
*
* @param tilte 指定图层的title
*/
var removeLayerExceptOne = function(map, title) {
var layers = map.getLayerGroup().getLayers()['a'];
for (var i = 0; i < layers.length; i++) {
console.log(layers[i]['U']['title']);
if (layers[i]['U']['title'] != 'China' && layers[i]['U']['title'] != title) {
console.log("remove" + layers[i]['U']['title']);
map.removeLayer(layers[i]);
}
}
}
/**
* 显示指定图层,隐藏其他图层
*
* @param {object} map
* @param {string} title
*/
var hiddenLayerExceptOne = function(map, title) {
var layers = map.getLayerGroup().getLayers()['a'];
for (var i = 0; i < layers.length; i++) {
console.log(layers[i]['U']['title']);
if (layers[i]['U']['title'] != 'China' && layers[i]['U']['title'] != title) {
console.log("hidden" + layers[i]['U']['title']);
var layer = layers[i];
layer.setVisible(false);
} else{
var layer = layers[i];
layer.setVisible(true);
}
}
}
/**
* 添加图层,并区分是否存在当前 title 值的图层
*
* @param {object} layer
* @param {string} title
*/
var addMapLayer = function(layer, title) {
if (!isLayerExist(title)) {
layer.setVisible(false);
map.addLayer(layer);
}
console.log('当前图层 title 已存在:'+ title);
}
/**
* 判断是否存在当前 title 的图层
* @param {string} title
*/
var isLayerExist = function (title) {
var layers = map.getLayerGroup().getLayers();
var layers_len = layers.length;
for (var i = 0; i < layers_len; i++) {
if (layers['a'][i]['U']['title'] == title) {
return true;
}
}
return false;
}

var trim = function(str) {
return str.replace(/(^\s*)|(\s*$)/g, "")
}
//返回的gisApi
var gisAPI = {
map: getMap,
setProj: setDeproj,
setCenter: setCoordinates,
setSource: setVectorLayerSource,
createGeoLayer: createGeoLayer,
createKMLLayer: createKMLLayer,
saveOnlyLayer: removeLayerExceptOne,
createGridGeoLayer: createGridGeoLayer,
createPercentGeoLayer: createPercentGeoLayer,
createDensityGeoLayer: createDensityGeoLayer,
viewLayer:hiddenLayerExceptOne,
addMapLayer: addMapLayer
};
return gisAPI;
}