-
Notifications
You must be signed in to change notification settings - Fork 179
Expand file tree
/
Copy patholHelpers.js
More file actions
1127 lines (983 loc) · 42.2 KB
/
olHelpers.js
File metadata and controls
1127 lines (983 loc) · 42.2 KB
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
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
angular.module('openlayers-directive').factory('olHelpers', function($q, $log, $http) {
var isDefined = function(value) {
return angular.isDefined(value);
};
var isDefinedAndNotNull = function(value) {
return angular.isDefined(value) && value !== null;
};
var setEvent = function(map, eventType, scope) {
map.on(eventType, function(event) {
var coord = event.coordinate;
var proj = map.getView().getProjection().getCode();
if (proj === 'pixel') {
coord = coord.map(function(v) {
return parseInt(v, 10);
});
}
scope.$emit('openlayers.map.' + eventType, {
'coord': coord,
'projection': proj,
'event': event
});
});
};
var bingImagerySets = [
'Road',
'Aerial',
'AerialWithLabels',
'collinsBart',
'ordnanceSurvey'
];
var getControlClasses = function() {
return {
attribution: ol.control.Attribution,
fullscreen: ol.control.FullScreen,
mouseposition: ol.control.MousePosition,
overviewmap: ol.control.OverviewMap,
rotate: ol.control.Rotate,
scaleline: ol.control.ScaleLine,
zoom: ol.control.Zoom,
zoomslider: ol.control.ZoomSlider,
zoomtoextent: ol.control.ZoomToExtent
};
};
var mapQuestLayers = ['osm', 'sat', 'hyb'];
var esriBaseLayers = ['World_Imagery', 'World_Street_Map', 'World_Topo_Map',
'World_Physical_Map', 'World_Terrain_Base',
'Ocean_Basemap', 'NatGeo_World_Map'];
var styleMap = {
'style': ol.style.Style,
'fill': ol.style.Fill,
'stroke': ol.style.Stroke,
'circle': ol.style.Circle,
'icon': ol.style.Icon,
'image': ol.style.Image,
'regularshape': ol.style.RegularShape,
'text': ol.style.Text
};
var optionalFactory = function(style, Constructor) {
if (Constructor && style instanceof Constructor) {
return style;
} else if (Constructor) {
return new Constructor(style);
} else {
return style;
}
};
//Parse the style tree calling the appropriate constructors.
//The keys in styleMap can be used and the OpenLayers constructors can be
//used directly.
var createStyle = function recursiveStyle(data, styleName) {
var style;
if (!styleName) {
styleName = 'style';
style = data;
} else {
style = data[styleName];
}
//Instead of defining one style for the layer, we've been given a style function
//to apply to each feature.
if (styleName === 'style' && data instanceof Function) {
return data;
}
if (!(style instanceof Object)) {
return style;
}
var styleObject;
if (Object.prototype.toString.call(style) === '[object Object]') {
styleObject = {};
var styleConstructor = styleMap[styleName];
if (styleConstructor && style instanceof styleConstructor) {
return style;
}
Object.getOwnPropertyNames(style).forEach(function(val, idx, array) {
//Consider the case
//image: {
// circle: {
// fill: {
// color: 'red'
// }
// }
//
//An ol.style.Circle is an instance of ol.style.Image, so we do not want to construct
//an Image and then construct a Circle. We assume that if we have an instanceof
//relationship, that the JSON parent has exactly one child.
//We check to see if an inheritance relationship exists.
//If it does, then for the parent we create an instance of the child.
var valConstructor = styleMap[val];
if (styleConstructor && valConstructor &&
valConstructor.prototype instanceof styleMap[styleName]) {
console.assert(array.length === 1, 'Extra parameters for ' + styleName);
styleObject = recursiveStyle(style, val);
return optionalFactory(styleObject, valConstructor);
} else {
styleObject[val] = recursiveStyle(style, val);
// if the value is 'text' and it contains a String, then it should be interpreted
// as such, 'cause the text style might effectively contain a text to display
if (val !== 'text' && typeof styleObject[val] !== 'string') {
styleObject[val] = optionalFactory(styleObject[val], styleMap[val]);
}
}
});
} else {
styleObject = style;
}
return optionalFactory(styleObject, styleMap[styleName]);
};
var detectLayerType = function(layer) {
if (layer.type) {
return layer.type;
} else {
switch (layer.source.type) {
case 'ImageWMS':
return 'Image';
case 'ImageStatic':
return 'Image';
case 'GeoJSON':
case 'JSONP':
case 'TopoJSON':
case 'KML':
case 'WKT':
return 'Vector';
case 'TileVector':
case 'MVT':
return 'TileVector';
default:
return 'Tile';
}
}
};
var createProjection = function(view) {
var oProjection;
switch (view.projection) {
case 'pixel':
if (!isDefined(view.extent)) {
$log.error('[AngularJS - Openlayers] - You must provide the extent of the image ' +
'if using pixel projection');
return;
}
oProjection = new ol.proj.Projection({
code: 'pixel',
units: 'pixels',
extent: view.extent
});
break;
default:
oProjection = new ol.proj.get(view.projection);
break;
}
return oProjection;
};
var isValidStamenLayer = function(layer) {
return ['watercolor', 'terrain', 'toner'].indexOf(layer) !== -1;
};
var createSource = function(source, projection) {
var oSource;
var pixelRatio;
var url;
var geojsonFormat = new ol.format.GeoJSON(); // used in various switch stmnts below
switch (source.type) {
case 'MapBox':
if (!source.mapId || !source.accessToken) {
$log.error('[AngularJS - Openlayers] - MapBox layer requires the map id and the access token');
return;
}
url = 'https://api.tiles.mapbox.com/v4/' + source.mapId + '/{z}/{x}/{y}.png?access_token=' +
source.accessToken;
pixelRatio = window.devicePixelRatio;
if (pixelRatio > 1) {
url = url.replace('.png', '@2x.png');
}
oSource = new ol.source.XYZ({
url: url,
tileLoadFunction: source.tileLoadFunction,
attributions: createAttribution(source),
tilePixelRatio: pixelRatio > 1 ? 2 : 1,
wrapX: source.wrapX !== undefined ? source.wrapX : true
});
break;
case 'MapBoxStudio':
if (!source.mapId || !source.accessToken || !source.userId) {
$log.error('[AngularJS - Openlayers] - MapBox Studio layer requires the map id' +
', user id and the access token');
return;
}
url = 'https://api.mapbox.com/styles/v1/' + source.userId +
'/' + source.mapId + '/tiles/{z}/{x}/{y}?access_token=' +
source.accessToken;
pixelRatio = window.devicePixelRatio;
if (pixelRatio > 1) {
url = url.replace('{y}?access_token', '{y}@2x?access_token');
}
oSource = new ol.source.XYZ({
url: url,
tileLoadFunction: source.tileLoadFunction,
attributions: createAttribution(source),
tilePixelRatio: pixelRatio > 1 ? 2 : 1,
tileSize: source.tileSize || [512, 512],
wrapX: source.wrapX !== undefined ? source.wrapX : true
});
break;
case 'MVT':
if (!source.url) {
$log.error('[AngularJS - Openlayers] - MVT layer requires the source url');
return;
}
oSource = new ol.source.VectorTile({
attributions: source.attributions || '',
format: new ol.format.MVT(),
tileGrid: ol.tilegrid.createXYZ({maxZoom: source.maxZoom || 22}),
tilePixelRatio: source.tilePixelRatio || 16,
url: source.url
});
break;
case 'ImageWMS':
if (!source.url || !source.params) {
$log.error('[AngularJS - Openlayers] - ImageWMS Layer needs ' +
'valid server url and params properties');
}
oSource = new ol.source.ImageWMS({
url: source.url,
imageLoadFunction: source.imageLoadFunction,
attributions: createAttribution(source),
crossOrigin: (typeof source.crossOrigin === 'undefined') ? 'anonymous' : source.crossOrigin,
params: deepCopy(source.params),
ratio: source.ratio
});
break;
case 'TileWMS':
if ((!source.url && !source.urls) || !source.params) {
$log.error('[AngularJS - Openlayers] - TileWMS Layer needs ' +
'valid url (or urls) and params properties');
}
var wmsConfiguration = {
tileLoadFunction: source.tileLoadFunction,
crossOrigin: (typeof source.crossOrigin === 'undefined') ? 'anonymous' : source.crossOrigin,
params: deepCopy(source.params),
attributions: createAttribution(source),
wrapX: source.wrapX !== undefined ? source.wrapX : true
};
if (source.serverType) {
wmsConfiguration.serverType = source.serverType;
}
if (source.url) {
wmsConfiguration.url = source.url;
}
if (source.urls) {
wmsConfiguration.urls = source.urls;
}
oSource = new ol.source.TileWMS(wmsConfiguration);
break;
case 'WMTS':
if ((!source.url && !source.urls) || !source.tileGrid) {
$log.error('[AngularJS - Openlayers] - WMTS Layer needs valid url ' +
'(or urls) and tileGrid properties');
}
var wmtsConfiguration = {
tileLoadFunction: source.tileLoadFunction,
projection: projection,
layer: source.layer,
attributions: createAttribution(source),
matrixSet: (source.matrixSet === 'undefined') ? projection : source.matrixSet,
format: (source.format === 'undefined') ? 'image/jpeg' : source.format,
requestEncoding: (source.requestEncoding === 'undefined') ?
'KVP' : source.requestEncoding,
tileGrid: new ol.tilegrid.WMTS({
origin: source.tileGrid.origin,
resolutions: source.tileGrid.resolutions,
matrixIds: source.tileGrid.matrixIds
}),
style: (source.style === 'undefined') ? 'normal' : source.style,
wrapX: source.wrapX !== undefined ? source.wrapX : true
};
if (isDefined(source.url)) {
wmtsConfiguration.url = source.url;
}
if (isDefined(source.urls)) {
wmtsConfiguration.urls = source.urls;
}
oSource = new ol.source.WMTS(wmtsConfiguration);
break;
case 'OSM':
oSource = new ol.source.OSM({
tileLoadFunction: source.tileLoadFunction,
attributions: createAttribution(source),
wrapX: source.wrapX !== undefined ? source.wrapX : true
});
if (source.url) {
oSource.setUrl(source.url);
}
break;
case 'BingMaps':
if (!source.key) {
$log.error('[AngularJS - Openlayers] - You need an API key to show the Bing Maps.');
return;
}
var bingConfiguration = {
key: source.key,
tileLoadFunction: source.tileLoadFunction,
attributions: createAttribution(source),
imagerySet: source.imagerySet ? source.imagerySet : bingImagerySets[0],
culture: source.culture,
wrapX: source.wrapX !== undefined ? source.wrapX : true
};
if (source.maxZoom) {
bingConfiguration.maxZoom = source.maxZoom;
}
oSource = new ol.source.BingMaps(bingConfiguration);
break;
case 'MapQuest':
if (!source.layer || mapQuestLayers.indexOf(source.layer) === -1) {
$log.error('[AngularJS - Openlayers] - MapQuest layers needs a valid \'layer\' property.');
return;
}
oSource = new ol.source.MapQuest({
attributions: createAttribution(source),
layer: source.layer,
wrapX: source.wrapX !== undefined ? source.wrapX : true
});
break;
case 'EsriBaseMaps':
if (!source.layer || esriBaseLayers.indexOf(source.layer) === -1) {
$log.error('[AngularJS - Openlayers] - ESRI layers needs a valid \'layer\' property.');
return;
}
var _urlBase = 'http://services.arcgisonline.com/ArcGIS/rest/services/';
var _url = _urlBase + source.layer + '/MapServer/tile/{z}/{y}/{x}';
oSource = new ol.source.XYZ({
attributions: createAttribution(source),
tileLoadFunction: source.tileLoadFunction,
url: _url,
wrapX: source.wrapX !== undefined ? source.wrapX : true
});
break;
case 'TileArcGISRest':
if (!source.url) {
$log.error('[AngularJS - Openlayers] - TileArcGISRest Layer needs valid url');
}
oSource = new ol.source.TileArcGISRest({
attributions: createAttribution(source),
tileLoadFunction: source.tileLoadFunction,
url: source.url,
wrapX: source.wrapX !== undefined ? source.wrapX : true
});
break;
case 'GeoJSON':
if (!(source.geojson || source.url)) {
$log.error('[AngularJS - Openlayers] - You need a geojson ' +
'property to add a GeoJSON layer.');
return;
}
if (isDefined(source.url)) {
oSource = new ol.source.Vector({
format: new ol.format.GeoJSON(),
url: source.url
});
} else {
oSource = new ol.source.Vector();
var projectionToUse = projection;
var dataProjection; // Projection of geojson data
if (isDefined(source.geojson.projection)) {
dataProjection = new ol.proj.get(source.geojson.projection);
} else {
dataProjection = projection; // If not defined, features will not be reprojected.
}
var features = geojsonFormat.readFeatures(
source.geojson.object, {
featureProjection: projectionToUse.getCode(),
dataProjection: dataProjection.getCode()
});
oSource.addFeatures(features);
}
break;
case 'WKT':
if (!(source.wkt) && !(source.wkt.data)) {
$log.error('[AngularJS - Openlayers] - You need a WKT ' +
'property to add a WKT format vector layer.');
return;
}
oSource = new ol.source.Vector();
var wktFormatter = new ol.format.WKT();
var wktProjection; // Projection of wkt data
if (isDefined(source.wkt.projection)) {
wktProjection = new ol.proj.get(source.wkt.projection);
} else {
wktProjection = projection; // If not defined, features will not be reprojected.
}
var wktFeatures = wktFormatter.readFeatures(
source.wkt.data, {
featureProjection: projection.getCode(),
dataProjection: wktProjection.getCode()
});
oSource.addFeatures(wktFeatures);
break;
case 'JSONP':
if (!(source.url)) {
$log.error('[AngularJS - Openlayers] - You need an url properly configured to add a JSONP layer.');
return;
}
if (isDefined(source.url)) {
oSource = new ol.source.ServerVector({
format: geojsonFormat,
loader: function(/*extent, resolution, projection*/) {
var url = source.url +
'&outputFormat=text/javascript&format_options=callback:JSON_CALLBACK';
$http.jsonp(url, { cache: source.cache})
.success(function(response) {
oSource.addFeatures(geojsonFormat.readFeatures(response));
})
.error(function(response) {
$log(response);
});
},
projection: projection
});
}
break;
case 'TopoJSON':
if (!(source.topojson || source.url)) {
$log.error('[AngularJS - Openlayers] - You need a topojson ' +
'property to add a TopoJSON layer.');
return;
}
if (source.url) {
oSource = new ol.source.Vector({
format: new ol.format.TopoJSON(),
url: source.url
});
} else {
oSource = new ol.source.Vector(angular.extend(source.topojson, {
format: new ol.format.TopoJSON()
}));
}
break;
case 'TileJSON':
oSource = new ol.source.TileJSON({
url: source.url,
attributions: createAttribution(source),
tileLoadFunction: source.tileLoadFunction,
crossOrigin: 'anonymous',
wrapX: source.wrapX !== undefined ? source.wrapX : true
});
break;
case 'TileVector':
if (!source.url || !source.format) {
$log.error('[AngularJS - Openlayers] - TileVector Layer needs valid url and format properties');
}
oSource = new ol.source.VectorTile({
url: source.url,
projection: projection,
attributions: createAttribution(source),
tileLoadFunction: source.tileLoadFunction,
format: source.format,
tileGrid: new ol.tilegrid.createXYZ({
maxZoom: source.maxZoom || 19
}),
wrapX: source.wrapX !== undefined ? source.wrapX : true
});
break;
case 'TileTMS':
if (!source.url || !source.tileGrid) {
$log.error('[AngularJS - Openlayers] - TileTMS Layer needs valid url and tileGrid properties');
}
oSource = new ol.source.TileImage({
url: source.url,
maxExtent: source.maxExtent,
attributions: createAttribution(source),
tileLoadFunction: source.tileLoadFunction,
tileGrid: new ol.tilegrid.TileGrid({
origin: source.tileGrid.origin,
resolutions: source.tileGrid.resolutions
}),
tileUrlFunction: function(tileCoord) {
var z = tileCoord[0];
var x = tileCoord[1];
var y = tileCoord[2]; //(1 << z) - tileCoord[2] - 1;
if (x < 0 || y < 0) {
return '';
}
var url = source.url + z + '/' + x + '/' + y + '.png';
return url;
},
wrapX: source.wrapX !== undefined ? source.wrapX : true
});
break;
case 'TileImage':
oSource = new ol.source.TileImage({
url: source.url,
attributions: createAttribution(source),
tileLoadFunction: source.tileLoadFunction,
tileGrid: new ol.tilegrid.TileGrid({
origin: source.tileGrid.origin, // top left corner of the pixel projection's extent
resolutions: source.tileGrid.resolutions
}),
tileUrlFunction: function(tileCoord/*, pixelRatio, projection*/) {
var z = tileCoord[0];
var x = tileCoord[1];
var y = -tileCoord[2] - 1;
var url = source.url
.replace('{z}', z.toString())
.replace('{x}', x.toString())
.replace('{y}', y.toString());
return url;
},
wrapX: source.wrapX !== undefined ? source.wrapX : true
});
break;
case 'KML':
var extractStyles = source.extractStyles || false;
oSource = new ol.source.Vector({
url: source.url,
format: new ol.format.KML(),
radius: source.radius,
extractStyles: extractStyles
});
break;
case 'Stamen':
if (!source.layer || !isValidStamenLayer(source.layer)) {
$log.error('[AngularJS - Openlayers] - You need a valid Stamen layer.');
return;
}
oSource = new ol.source.Stamen({
tileLoadFunction: source.tileLoadFunction,
layer: source.layer,
wrapX: source.wrapX !== undefined ? source.wrapX : true
});
break;
case 'ImageStatic':
if (!source.url || !angular.isArray(source.imageSize) || source.imageSize.length !== 2) {
$log.error('[AngularJS - Openlayers] - You need a image URL to create a ImageStatic layer.');
return;
}
oSource = new ol.source.ImageStatic({
url: source.url,
attributions: createAttribution(source),
imageSize: source.imageSize,
projection: projection,
imageExtent: source.imageExtent ? source.imageExtent : projection.getExtent(),
imageLoadFunction: source.imageLoadFunction
});
break;
case 'XYZ':
if (!source.url && !source.tileUrlFunction) {
$log.error('[AngularJS - Openlayers] - XYZ Layer needs valid url or tileUrlFunction properties');
}
oSource = new ol.source.XYZ({
url: source.url,
attributions: createAttribution(source),
minZoom: source.minZoom,
maxZoom: source.maxZoom,
projection: source.projection,
tileUrlFunction: source.tileUrlFunction,
tileLoadFunction: source.tileLoadFunction,
wrapX: source.wrapX !== undefined ? source.wrapX : true
});
break;
case 'Zoomify':
if (!source.url || !angular.isArray(source.imageSize) || source.imageSize.length !== 2) {
$log.error('[AngularJS - Openlayers] - Zoomify Layer needs valid url and imageSize properties');
}
oSource = new ol.source.Zoomify({
url: source.url,
size: source.imageSize,
wrapX: source.wrapX !== undefined ? source.wrapX : true
});
break;
}
// log a warning when no source could be created for the given type
if (!oSource) {
$log.warn('[AngularJS - Openlayers] - No source could be found for type "' + source.type + '"');
}
return oSource;
};
var deepCopy = function(oldObj) {
var newObj = oldObj;
if (oldObj && typeof oldObj === 'object') {
newObj = Object.prototype.toString.call(oldObj) === '[object Array]' ? [] : {};
for (var i in oldObj) {
newObj[i] = deepCopy(oldObj[i]);
}
}
return newObj;
};
var createAttribution = function(source) {
var attributions = [];
if (isDefined(source.attribution)) {
attributions.unshift(new ol.Attribution({html: source.attribution}));
}
return attributions;
};
var createGroup = function(name) {
var olGroup = new ol.layer.Group();
olGroup.set('name', name);
return olGroup;
};
var getGroup = function(layers, name) {
var layer;
angular.forEach(layers, function(l) {
if (l instanceof ol.layer.Group && l.get('name') === name) {
layer = l;
return;
}
});
return layer;
};
var addLayerBeforeMarkers = function(layers, layer) {
var markersIndex;
for (var i = 0; i < layers.getLength(); i++) {
var l = layers.item(i);
if (l.get('markers')) {
markersIndex = i;
break;
}
}
if (isDefined(markersIndex)) {
var markers = layers.item(markersIndex);
layer.index = markersIndex;
layers.setAt(markersIndex, layer);
markers.index = layers.getLength();
layers.push(markers);
} else {
layer.index = layers.getLength();
layers.push(layer);
}
};
var removeLayer = function(layers, index) {
layers.removeAt(index);
for (var i = index; i < layers.getLength(); i++) {
var l = layers.item(i);
if (l === null) {
layers.insertAt(i, null);
break;
} else {
l.index = i;
}
}
};
return {
// Determine if a reference is defined
isDefined: isDefined,
// Determine if a reference is a number
isNumber: function(value) {
return angular.isNumber(value);
},
createView: function(view) {
var projection = createProjection(view);
var viewConfig = {
projection: projection,
maxZoom: view.maxZoom,
minZoom: view.minZoom
};
if (view.center) {
viewConfig.center = view.center;
}
if (view.extent) {
viewConfig.extent = view.extent;
}
if (view.zoom) {
viewConfig.zoom = view.zoom;
}
if (view.resolutions) {
viewConfig.resolutions = view.resolutions;
}
return new ol.View(viewConfig);
},
// Determine if a reference is defined and not null
isDefinedAndNotNull: isDefinedAndNotNull,
// Determine if a reference is a string
isString: function(value) {
return angular.isString(value);
},
// Determine if a reference is an array
isArray: function(value) {
return angular.isArray(value);
},
// Determine if a reference is an object
isObject: function(value) {
return angular.isObject(value);
},
// Determine if two objects have the same properties
equals: function(o1, o2) {
return angular.equals(o1, o2);
},
isValidCenter: function(center) {
return angular.isDefined(center) &&
(typeof center.autodiscover === 'boolean' ||
angular.isNumber(center.lat) && angular.isNumber(center.lon) ||
(angular.isArray(center.coord) && center.coord.length === 2 &&
angular.isNumber(center.coord[0]) && angular.isNumber(center.coord[1])) ||
(angular.isArray(center.bounds) && center.bounds.length === 4 &&
angular.isNumber(center.bounds[0]) && angular.isNumber(center.bounds[1]) &&
angular.isNumber(center.bounds[1]) && angular.isNumber(center.bounds[2])));
},
safeApply: function($scope, fn) {
var phase = $scope.$root.$$phase;
if (phase === '$apply' || phase === '$digest') {
$scope.$eval(fn);
} else {
$scope.$apply(fn);
}
},
isSameCenterOnMap: function(center, map) {
var urlProj = center.projection || 'EPSG:4326';
var urlCenter = [center.lon, center.lat];
var mapProj = map.getView().getProjection();
var mapCenter = ol.proj.transform(map.getView().getCenter(), mapProj, urlProj);
var zoom = map.getView().getZoom();
if (mapCenter[1].toFixed(4) === urlCenter[1].toFixed(4) &&
mapCenter[0].toFixed(4) === urlCenter[0].toFixed(4) &&
zoom === center.zoom) {
return true;
}
return false;
},
setCenter: function(view, projection, newCenter) {
var coord = [newCenter.lon, newCenter.lat];
if (newCenter.projection === projection) {
view.setCenter(coord);
} else {
view.setCenter(ol.proj.transform(coord, newCenter.projection, projection));
}
},
setZoom: function(view, zoom) {
view.setZoom(zoom);
},
isBoolean: function(value) {
return typeof value === 'boolean';
},
createStyle: createStyle,
setMapEvents: function(events, map, scope) {
if (isDefined(events) && angular.isArray(events.map)) {
for (var i in events.map) {
var event = events.map[i];
setEvent(map, event, scope);
}
}
},
setVectorLayerEvents: function(events, map, scope, layerName) {
if (isDefined(events) && angular.isArray(events.layers)) {
angular.forEach(events.layers, function(eventType) {
angular.element(map.getViewport()).on(eventType, function(evt) {
var pixel = map.getEventPixel(evt);
var feature = map.forEachFeatureAtPixel(pixel, function(feature, olLayer) {
// only return the feature if it is in this layer (based on the name)
return (isDefinedAndNotNull(olLayer) && olLayer.get('name') === layerName) ? feature : null;
});
if (isDefinedAndNotNull(feature)) {
scope.$emit('openlayers.layers.' + layerName + '.' + eventType, feature, evt);
}
});
});
}
},
setViewEvents: function(events, map, scope) {
if (isDefined(events) && angular.isArray(events.view)) {
var view = map.getView();
angular.forEach(events.view, function(eventType) {
view.on(eventType, function(event) {
scope.$emit('openlayers.view.' + eventType, view, event);
});
});
}
},
detectLayerType: detectLayerType,
createLayer: function(layer, projection, name, onLayerCreatedFn) {
var oLayer;
var type = detectLayerType(layer);
var oSource = createSource(layer.source, projection);
if (!oSource) {
return;
}
// handle function overloading. 'name' argument may be
// our onLayerCreateFn since name is optional
if (typeof(name) === 'function' && !onLayerCreatedFn) {
onLayerCreatedFn = name;
name = undefined; // reset, otherwise it'll be used later on
}
// Manage clustering
if ((type === 'Vector') && layer.clustering) {
oSource = new ol.source.Cluster({
source: oSource,
distance: layer.clusteringDistance
});
}
var layerConfig = {};
// copy over eventual properties set on the passed layerconfig which
// can later be retrieved via layer.get('propName');
for (var property in layer) {
if (layer.hasOwnProperty(property) &&
// ignore props like source or those angular might add (starting with $)
// don't use startsWith as it is not supported in IE
property.indexOf('$', 0) !== 0 &&
property.indexOf('source', 0) !== 0 &&
property.indexOf('style', 0) !== 0
) {
layerConfig[property] = layer[property];
}
}
layerConfig.source = oSource;
// ol.layer.Layer configuration options
if (isDefinedAndNotNull(layer.opacity)) {
layerConfig.opacity = layer.opacity;
}
if (isDefinedAndNotNull(layer.visible)) {
layerConfig.visible = layer.visible;
}
if (isDefinedAndNotNull(layer.extent)) {
layerConfig.extent = layer.extent;
}
if (isDefinedAndNotNull(layer.zIndex)) {
layerConfig.zIndex = layer.zIndex;
}
if (isDefinedAndNotNull(layer.minResolution)) {
layerConfig.minResolution = layer.minResolution;
}
if (isDefinedAndNotNull(layer.maxResolution)) {
layerConfig.maxResolution = layer.maxResolution;
}
if (isDefinedAndNotNull(layer.style) && type === 'TileVector') {
layerConfig.style = layer.style;
}
switch (type) {
case 'Image':
oLayer = new ol.layer.Image(layerConfig);
break;
case 'Tile':
oLayer = new ol.layer.Tile(layerConfig);
break;
case 'Heatmap':
oLayer = new ol.layer.Heatmap(layerConfig);
break;
case 'Vector':
oLayer = new ol.layer.Vector(layerConfig);
break;
case 'TileVector':
oLayer = new ol.layer.VectorTile(layerConfig);
break;
}
// set a layer name if given
if (isDefined(name)) {
oLayer.set('name', name);
} else if (isDefined(layer.name)) {
oLayer.set('name', layer.name);
}
// set custom layer properties if given
if (isDefined(layer.customAttributes)) {
for (var key in layer.customAttributes) {
oLayer.set(key, layer.customAttributes[key]);
}
}
// invoke the onSourceCreated callback
if (onLayerCreatedFn) {
onLayerCreatedFn({
oLayer: oLayer
});
}
return oLayer;
},