This repository has been archived by the owner on May 24, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
om.js
917 lines (905 loc) · 33.1 KB
/
om.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
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
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
/**
* 基于openlayers v4.0.1 的简单封装。
* simple package based on openlayers v4.0.1.
* @author lucienlugeek lucienlugeek@gmail.com
* @description provide common functions on map.
*/
(function(root, factory) {
if (typeof exports === 'object') {
module.exports = factory();
} else if (typeof define === 'function' && define.amd) {
define(['ol'], factory);
} else {
root.OpenMap = factory(root.ol);
}
}(this, function(ol) {
'use strict';
/**
* OpenMap的初始化入口。
* constructor of OpenMap.
* @class OpenMap
* @constructor
*/
let OpenMap = function(...args) {
if (args.length) {
this.init.apply(this, ...args);
} else {
throw new Error('Parameter should not be null!');
}
};
/**
* 检查类型
* **注意**:NaN会判断为Number类型
* Check type
* **Be aware**: NaN belongs to Number
* @method OpenMap.is
* @param {Object} toBeChecked parameter to be checked
* @param {String}
* type Object,Array,String,RegExp,Boolean,Number,Function,Null,Undefined
* @return {boolean} {{布尔值:是否符合检测条件}}{{}}
*/
OpenMap.is = function(toBeChecked, type) {
return Object.prototype.toString.call((toBeChecked)) ===
'[object ' + type + ']';
};
/**
* 根据坐标对象数组获取闭包范围
* Obtain extent based on data array
* @method OpenMap.getExtentByDataArray
* @param {Object[]} data [{lon:131.00,lat:30},...]
* @return {number[]} extent [minx,miny,maxx, maxy]
*/
OpenMap.getExtentByDataArray = function(data) {
let minx = 180;
let miny = 180;
let maxx = 0.0;
let maxy = 0.0;
let tmpx = 0.0;
let tmpy = 0.0;
let len = data.length;
for (let p = 0; p < len; p++) {
tmpx = parseFloat(data[p]['lon']);
if (tmpx >= maxx) {
maxx = tmpx;
}
if (tmpx < minx) {
minx = tmpx;
}
tmpy = parseFloat(data[p]['lat']);
if (tmpy >= maxy) {
maxy = tmpy;
}
if (tmpy <= miny) {
miny = tmpy;
}
}
return [minx, miny, maxx, maxy];
};
/**
* 根据坐标数组获取闭包范围
* Obtain extent based on coordinates array
* @method OpenMap.getExtentByCoordinates
* @param {Array.<number[]>} data coordinates array [[131.00,30],...]
* @return {number[]} extent [minx,miny,maxx, maxy]
*/
OpenMap.getExtentByCoordinates = function(data) {
let minx = 180;
let miny = 180;
let maxx = 0.0;
let maxy = 0.0;
let tmpx = 0.0;
let tmpy = 0.0;
let len = data.length;
for (let p = 0; p < len; p++) {
tmpx = parseFloat(data[p][0]);
if (tmpx >= maxx) {
maxx = tmpx;
}
if (tmpx < minx) {
minx = tmpx;
}
tmpy = parseFloat(data[p][1]);
if (tmpy >= maxy) {
maxy = tmpy;
}
if (tmpy <= miny) {
miny = tmpy;
}
}
return [minx, miny, maxx, maxy];
};
/**
* 计算半径的长度(单位米)
* Calculate radius(meter)
* @method OpenMap.calcRadius
* @param {Object} map object
* @param {Object} event
* @return {number} distance(meter)
*/
OpenMap.calcRadius = function(map, event) {
event.feature.set('type', 'circle');
let center = event.feature.getGeometry().getCenter();
let start = center;
let end = event.feature.getGeometry().getLastCoordinate();
let mapProjection = map.getView().getProjection();
let t1 = ol.proj.transform(start, mapProjection, 'EPSG:4326');
let t2 = ol.proj.transform(end, mapProjection, 'EPSG:4326');
// create sphere to measure on
// one of WGS84 earth radius
let wgs84sphere = new ol.Sphere(6378137);
// get distance on sphere
let dist = wgs84sphere.haversineDistance(t1, t2);
dist = dist.toFixed(6); // unit meter
return dist;
};
/**
* 计算两点之间的距离(单位米)
* Calculate distance of two points(meter)
* @method OpenMap.calcDistance
* @param {Object} start
* @param {Object} end
* @return {number} distance(meter)
*/
OpenMap.calcDistance = function(start, end) {
// create sphere to measure on
// one of WGS84 earth radius'
let wgs84sphere = new ol.Sphere(6378137);
// get distance on sphere
let dist = wgs84sphere.haversineDistance(start, end);
dist = dist.toFixed(6); // unit meter
return dist;
};
/**
* 计算多边形面积(单位平方米)
* Calculate area of polygon (square meter)
* @method OpenMap.calcArea
* @param {Object} polygon
* @return {number} area(square meter)
*/
OpenMap.calcArea = function(polygon) {
let wgs84sphere = new ol.Sphere(6378137);
let coordinates = polygon.getLinearRing(0).getCoordinates();
return Math.abs(wgs84sphere.geodesicArea(coordinates));
};
OpenMap.prototype = {
constructor: OpenMap,
/**
* 初始化图层组
* Initialize layer
* @method globalGroupLayer
* @param {Object} options
* @param {String} options.mapUrl url of layer
* @param {String} options.layers name of layer
* @return {Object} ol.layer.Group
*/
globalGroupLayer: function(options) {
if (typeof options === 'undefined' ||
typeof options.mapUrl === 'undefined' ||
typeof options.layers === 'undefined') {
throw new Error('invalid options.');
}
return new ol.layer.Group({
layers: [
new ol.layer.Image({
source: new ol.source.ImageWMS({
ratio: 1,
url: options.mapUrl,
crossOrigin: 'anonymous',
params: {
'FORMAT': options.format || 'image/png',
'VERSION': options.version || '1.1.0',
'LAYERS': options.layers,
},
}),
}),
],
});
},
/**
* 初始化图片层
* Initialize image layer
* @method globalImageLayer
* @param {Object} options
* @param {String} options.mapUrl url of layer
* @param {String} options.layers name of layer
* @return {Object} ol.layer.Image
*/
globalImageLayer: function(options) {
if (typeof options === 'undefined' ||
typeof options.mapUrl === 'undefined' ||
typeof options.layers === 'undefined') {
throw new Error('invalid options.');
}
return new ol.layer.Image({
source: new ol.source.ImageWMS({
ratio: 1,
url: options.mapUrl,
crossOrigin: 'anonymous',
params: {
'FORMAT': options.format || 'image/png',
'VERSION': options.version || '1.1.0',
'LAYERS': options.layers,
},
}),
});
},
/**
* 初始化瓦片层
* Initialize tile layer
* @method globalTileLayer
* @param {Object} options
* @param {String} options.mapUrl url of layer
* @param {String} options.layers name of layer
* @param {String} options.srs coordinate system
* @param {Object} options.resolutions array of resolution
* @param {Object} options.origin coordinate array for extent
* @return {Object} ol.layer.Tile
*/
globalTileLayer: function(options) {
if (typeof options === 'undefined' ||
typeof options.mapUrl === 'undefined' ||
typeof options.layers === 'undefined' ||
typeof options.srs === 'undefined' ||
typeof options.resolutions === 'undefined' ||
typeof options.origin === 'undefined') {
throw new Error('invalid options.');
}
return new ol.layer.Tile({
source: new ol.source.TileWMS({
url: options.mapUrl,
crossOrigin: 'anonymous',
params: {
'FORMAT': options.format || 'image/png',
'VERSION': options.version || '1.1.0',
'LAYERS': options.layers,
'SRS': options.srs,
},
tileGrid: ol.tilegrid.TileGrid({
minZoom: options.minZoom || 0,
maxZoom: options.maxZoom || 9,
resolutions: options.resolutions, // [0.00068664552062088911, 0.00034332276031044456, 0.00017166138015522228]
origin: options.origin, // [-180.0, 90.0]
}),
}),
});
},
/**
* 初始化热力图层
* Initialize thermodynamic diagram layer
* @method globalHeatmapLayer
* @param {Object} options
* @param {String} options.data [{lon:131.00,lat:31.00,weight:11},...]
* @return {Object} ol.layer.Heatmap
*/
globalHeatmapLayer: function(options) {
let features = [];
if (options && options.data) {
$.each(options.data, function(index, tempData) {
let coordinates = [parseFloat(tempData['lon']), parseFloat(tempData['lat'])];
features[index] = new ol.Feature({
geometry: new ol.geom.Point(coordinates),
weight: tempData['weight'],
});
});
}
return new ol.layer.Heatmap({
source: new ol.source.Vector({
features: features,
}),
gradient: options && options.gradient || ['#00f', '#0ff', '#0f0', '#ff0', '#f00'],
blur: options && options.blur || 30,
radius: options && options.radius || 30,
});
},
/**
* 初始化vector layer
* @method globalVectorLayer
* @param {Object} options
* @param {String} options.type Point(点), LineString(线),Circle(圆) ,Polygon(多边形)
* @return {Object} ol.layer.Vector
*/
globalVectorLayer: function(options) {
let self = this;
if (typeof options === 'undefined' ||
typeof options.type === 'undefined') {
throw new Error('invalid options.');
}
return new ol.layer.Vector({
source: new ol.source.Vector(),
style: options.style || function(feature) {
// type: Point(点), LineString(线),Circle(圆) ,Polygon(多边形)
if (options.type == 'Point') {
return self.getPointStyle();
} else {
return self.getPolyStyle();
}
},
});
},
/**
* 根据指定参数,初始化地图到容器中
* Initialize map to container
* @method init
* @param {String} id - The map container's ID
* @param {Object} options - options
* @param {number[]} options.center - center i.e: [120.561477,31.883179]
* @param {number} [options.zoom] - zoom lever i.e: 15
* @param {Object[]} [options.layers] - layers to be rendered i.e: [grouplayer,poiLayer]
* @param {Object} [options.projection] - projection i.e: new ol.proj.Projection({code: 'EPSG:4326',units: 'degrees',});
*/
init: function(id, options) {
let ele = document.getElementById(typeof id === 'undefined' ? '' : id);
if (ele === null) {
console.error('Cannot find DOM which id is ' + id);
return;
}
let self = this;
let param = $.extend({}, options);
self._map = new ol.Map({
target: ele,
loadTilesWhileAnimating: true,
view: new ol.View({
center: param.center,
zoom: param.zoom || 10,
minZoom: param.minZoom || 12,
maxZoom: param.maxZoom || 20,
projection: param.projection,
extent: param.extent,
}),
layers: param.layers || [],
extent: param.extent,
});
// preserve all layers
self._layer = {};
},
/**
* 获取地图对象
* Get map
* @method getMap
* @return {Object} map object
*/
getMap: function() {
return this._map;
},
/**
* 获取投影
* Get projection
* @method getProjection
* @return {Object} projection
*/
getProjection: function() {
return this._map.getView().getProjection();
},
/**
* 获取投影编码
* Get projection code
* @method getProjectionCode
* @return {String} projection code
*/
getProjectionCode: function() {
return this.getProjection().getCode();
},
/**
* 设置点默认样式
* Get default style of Point
* @method getPointStyle
* @return {Object} style
*/
getPointStyle: function() {
return new ol.style.Style({
image: new ol.style.Circle({
radius: 5,
fill: new ol.style.Fill({
color: 'rgba(255, 255, 255, 0.6)',
}),
stroke: new ol.style.Stroke({
color: 'rgba(0, 255, 255, 0.6)',
}),
image: new ol.style.Circle({
radius: 4,
fill: new ol.style.Fill({
color: '#FF0000',
}),
}),
}),
});
},
/**
* 设置线面默认样式
* Get style of polygon
* @method getPolyStyle
* @return {Object} style
*/
getPolyStyle: function() {
return new ol.style.Style({
fill: new ol.style.Fill({
color: 'rgba(255, 255, 255, 0.6)',
}),
stroke: new ol.style.Stroke({
color: 'rgba(0, 255, 255, 0.6)',
}),
});
},
/**
* 添加层
* add layer to map
* @method addLayer
* @param {String} layerName Name of layer
* @param {Object} layerObj layer instance
* @param {bollean} force whether to force update layer
* @return {Object} layer
*/
addLayer: function(layerName, layerObj, force) {
if (force) {
if (arguments.length !== 3) return;
this._layer[layerName] = layerObj;
this._map.removeLayer(layerName);
this._map.addLayer(layerObj);
} else {
if (arguments.length !== 2) return;
if (this.getLayer(layerName)) return;
this._layer[layerName] = layerObj;
this._map.addLayer(layerObj);
}
return layerObj;
},
/**
* 获取层
* get layer
* @method getLayer
* @param {String} layerName name of layer
* @return {Object} layer
*/
getLayer: function(layerName) {
return this._layer[layerName];
},
/**
* 移除层
* remove layer
* @method getLayer
* @param {String} layerName name of layer
*/
removeLayer: function(layerName) {
this._map.removeLayer(this.getLayer(layerName));
this._layer[layerName] = null;
delete this._layer[layerName];
},
/**
* 向地图添加标记
* add marker to map
* @method addMarker
* @param {Object} option options for creating marker
* @param {string} option.id id for marker
* @param {string} option.image image url for marker
* @param {number[]} option.position coordinates for marker
* @param {string} option.layerName name of the layer which the marker attached to
* @param {number|undefined} option.zIndex zIndex of layer
* @param {boolean|undefined} option.visible whether display layer
* @return {Object} marker
*/
addMarker: function(option) {
if (typeof option === 'undefined' ||
typeof option.position === 'undefined' ||
typeof option.layerName === 'undefined') {
console.error('invalid option');
return;
}
let self = this;
let _layer = self.getLayer(option.layerName);
if (!_layer) {
_layer = new ol.layer.Vector({
source: new ol.source.Vector({
features: [],
overlaps: false,
}),
style: (function() {
let style = new ol.style.Style({
text: new ol.style.Text({
font: '12px Calibri,sans-serif',
fill: new ol.style.Fill({
color: '#000',
}),
stroke: new ol.style.Stroke({
color: '#fff',
width: 3,
}),
text: '',
}),
});
return function(feature) {
style.setImage(new ol.style.Icon({
rotation: fea.get('rotation') || 0,
src: fea.get('image'),
anchor: fea.get('anchor'),
}));
style.getText().setText(feature.get('text'));
return style;
};
})(),
zIndex: (typeof option.zIndex !== 'undefined' ? option.zIndex : 0),
});
self.addLayer(option.layerName, _layer);
}
let prop = $.extend({}, option, {
geometry: new ol.geom.Point(option.position),
});
let fea = new ol.Feature(prop);
fea.setId(option.id);
_layer.getSource().addFeature(fea);
if (option.visible !== undefined) {
_layer.setVisible(option.visible);
}
return fea;
},
/**
* 向地图添加多个标记
* add markers to map
* @method addMarkers
* @param {Object} options
*/
addMarkers: function(options) {
if (typeof options === 'undefined' ||
typeof options.data === 'undefined' ||
typeof options.layerName === 'undefined') {
console.error('必须指定marker的图层名称!');
return;
}
let self = this;
let _layer = this._layer[options.layerName];
if (!_layer) {
_layer = new ol.layer.Vector({
source: new ol.source.Vector(),
projection: self.getProjection(),
style: (function() {
let style = new ol.style.Style({
text: new ol.style.Text({
font: '12px Calibri,sans-serif',
fill: new ol.style.Fill({
color: '#000',
}),
stroke: new ol.style.Stroke({
color: '#fff',
width: 3,
}),
text: '',
}),
});
return function(feature) {
style.setImage(new ol.style.Icon({
rotation: feature.get('rotation') || 0,
src: feature.get('image'),
anchor: feature.get('anchor') || [0, 0],
}));
style.getText().setText(feature.get('text'));
};
})(),
});
}
let features = [];
options.data.forEach(function(tempData, index) {
let coordinates = [parseFloat(tempData['lon']), parseFloat(tempData['lat'])];
features.push(new ol.Feature({
geometry: new ol.geom.Point(coordinates),
image: tempData['image'],
selfData: tempData,
}));
});
_layer.getSource().addFeatures(features);
this._map.addLayer(_layer);
},
/**
* 根据ID获取标记
* get marker by ID
* @method getMarkerById
* @param {String} id marker's id
* @return {Object} marker
*/
getMarkerById: function(id) {
if (typeof id === 'undefined') {
console.error('id cannot be undefined!');
return;
}
let self = this;
for (let l in self._layer) {
if (self._layer.hasOwnProperty(l)) {
let f = self._layer[l].getSource().getFeatureById(id);
if (f) {
return f;
} else {
continue;
}
}
}
return null;
},
/**
* 添加聚合图层
* add cluster to map
* @method addCluster
* @deprecated this method is not very common for use
* @param {Object} arg options for creating cluster
*/
addCluster: function(arg) {
if (typeof arg === 'undefined' || !OpenMap.is(arg, 'Array')) {
console.error('arg should be a valid array!');
return;
}
let self = this;
let len = arg.length;
let features = new Array(len);
let la;
let vi; // layername visible
for (let i = 0; i < len; i++) {
if (!la) {
la = arg[i].layerName;
}
if (!vi) {
vi = arg[i].visible;
}
let coordinates = arg[i].coordinates;
coordinates[0] = Number(coordinates[0]);
coordinates[1] = Number(coordinates[1]);
features[i] = new ol.Feature({
geometry: new ol.geom.Point(coordinates),
status: !!arg[i].isTrue, // online offline
});
}
let source = new ol.source.Vector({
features: features,
projection: self.getProjection(),
});
let clusterSource = new ol.source.Cluster({
distance: 100,
source: source,
});
let _layer = new ol.layer.Vector({
source: clusterSource,
style: function(feature) {
let feas = feature.get('features');
let i = 0;
let normalSize = 0;
let size = feas.length;
for (; i < size; i++) {
normalSize = normalSize +
(feas[i].getProperties().status);
}
let rO;
let rI;
if (size >= 100) {
rO = 44;
rI = 33;
} else if (size >= 10 && size <= 99) {
rO = 32;
rI = 24;
} else {
rO = 28;
rI = 18;
}
style = new ol.style.Style({
image: new ol.style.Icon({
img: dcanvas($('canvas.process').clone().show().get(0), {
'centerX': '45',
'centerY': '45',
'radiusOutside': rO,
'radiusInside': rI,
'normalSize': normalSize,
'size': size,
}),
imgSize: [90, 90],
}),
});
return style;
},
});
self.addLayer(la, _layer).setVisible(vi);
},
/**
* 添加覆盖元素
* add overlay to map
* @method addOverLay
* @param {Object} option options for creating overlay
* @return {object} overlay instance
*/
addOverLay: function(option) {
if (!option || !option.position || !option.eid) {
console.error('invalid param');
return;
}
let self = this;
let element = document.getElementById(option.eid);
if (option.hide) {
element.style.display = 'none';
} else {
element.style.display = 'block';
}
let popup = new ol.Overlay({
id: option.id,
position: option.position,
element: element,
stopEvent: typeof option.stopEvent !== 'undefined' ? option.stopEvent : true,
offset: option.offset || [0, 0],
positioning: option.positioning || 'center-center', // default center
});
self._map.addOverlay(popup);
return popup;
},
/**
* 获取覆盖元素
* get overlay
* @method getOverlay
* @param {String} id id of overlay
* @return {(Object|Array)} a specific overlay or all overlays
*/
getOverlay: function(...args) {
if (args.length === 0) {
return this._map.getOverlays().getArray();
} else {
let id = args[0];
let ov = this._map.getOverlayById(id);
return ov ? [ov] : [];
}
},
/**
* 删除Overlay:id 中包含参数domid的所有overlay
* remove overlay(s) which element's id contains domid
* @method removeOverlayByIndexOfId
* @param {String} domid
*/
removeOverlayByIndexOfId: function(domid) {
let self = this;
let overlayArr = this._map.getOverlays().getArray();
for (let i = overlayArr.length - 1; i >= 0; i--) {
let ilid = overlayArr[i].getElement().id;
if (ilid.indexOf(domid) != -1) {
self._map.removeOverlay(overlayArr[i]);
}
}
},
/**
* 移除标记
* remove marker
* @method removeMarker
* @param {Object} m the specific marker instance
*/
removeMarker: function(m) {
if (typeof m === 'undefined' || !OpenMap.is(m, 'Object')) {
console.error('invalid param');
return;
}
let layerName = m.getProperties()['layerName'];
let layer = this.getLayer(layerName);
if (layer) {
layer.getSource().removeFeature(m);
}
},
/**
* 移除指定图层上的所有标记
* remove all markers on the specific layer
* @method removeMarkerByLayer
* @param {string} layerName
*/
removeMarkerByLayer: function(layerName) {
if (typeof layerName === 'undefined') {
console.error('layer name cannot be null!');
return;
}
let layer = this.getLayer(layerName);
if (layer) {
layer.getSource().clear();
}
},
/**
* 移除指定id的标记
* remove marker with specific id
* @method removeMarkerById
* @param {string} id id of the marker to be removed
*/
removeMarkerById: function(id) {
if (typeof id === 'undefined') {
console.error('marker\'s id cannot be null!');
return;
}
let self = this;
for (let l in self._layer) {
if (self._layer.hasOwnProperty(l)) {
let f = self._layer[l].getSource().getFeatureById(id);
if (f) {
self._layer[l].getSource().removeFeature(f);
break;
}
}
}
},
/**
* 添加图层的监听事件
* add listener on layer
* @method addLayerListener
* @param {Object} layer
* @return{object} layerSelect instance
*/
addLayerListener: function(layer) {
let layerSelect = new ol.interaction.Select({
condition: ol.events.condition.singleClick,
layers: [layer],
style: function(fea) { // prevent style change
return new ol.style.Style({
image: new ol.style.Icon({
anchor: fea.get('anchor'),
rotation: fea.get('rotation'),
src: fea.get('image'),
}),
});
},
});
layerSelect.on('select', function(evt) {
if (evt.selected.length === 0) {
return;
}
evt.selected.forEach(function(feature) {
let clickFun = feature.getProperties().onClick;
clickFun ? clickFun.call(feature, feature) : null;
});
});
this._map.addInteraction(layerSelect);
return layerSelect;
},
/**
* 开启绘画功能
* open draw function
* @method openDraw
* @param {String} type 点、线、矩形、多边形、圆(Point|LineString|Box|Polygon|Circle)
* @param {events} events drawstart,drawend,change,propertychange
*/
openDraw: function(type, events) {
if (typeof type === 'undefined' || ['Point', 'LineString', 'Box', 'Polygon', 'Circle'].indexOf(type) === -1) {
console.error('draw type is error!');
return;
}
let self = this;
let map = self.getMap();
let source = new ol.source.Vector({
wrapX: false,
});
let _drawLayer = new ol.layer.Vector({
source: source,
});
self.addLayer('_drawLayer', _drawLayer);
self._draw = new ol.interaction.Draw({
source: source,
type: /** @type {ol.geom.GeometryType} */ (type === 'Box' ? 'Circle' : type),
geometryFunction: type === 'Box' ? ol.interaction.Draw.createBox() : undefined,
});
map.addInteraction(self._draw);
if (events && !OpenMap.is(events, 'Object')) {
console.warn('Event parameter is invalid!');
} else {
for (let e in events) {
if (events.hasOwnProperty(e)) {
// self._draw.dispatchEvent(e);
self._draw.on(e, events[e]);
}
}
}
},
/**
* 返回绘画对象
* get draw instance
* @method getDraw
* @return {Object} draw instance
*/
getDraw: function() {
return this._draw;
},
/**
* 关闭绘画功能
* close draw function
* @method closeDraw
*/
closeDraw: function() {
if (this._draw) {
this._map.removeInteraction(this._draw);
}
},
};
return OpenMap;
}));