forked from tombatossals/angular-leaflet-directive
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathangular-leaflet-directive.js
3768 lines (3395 loc) · 160 KB
/
angular-leaflet-directive.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
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
(function() {
"use strict";
angular.module("leaflet-directive", []).directive('leaflet', ["$q", "leafletData", "leafletMapDefaults", "leafletHelpers", "leafletEvents", function ($q, leafletData, leafletMapDefaults, leafletHelpers, leafletEvents) {
var _leafletMap;
return {
restrict: "EA",
replace: true,
scope: {
center : '=center',
defaults : '=defaults',
maxbounds : '=maxbounds',
bounds : '=bounds',
markers : '=markers',
legend : '=legend',
geojson : '=geojson',
paths : '=paths',
tiles : '=tiles',
layers : '=layers',
controls : '=controls',
decorations : '=decorations',
eventBroadcast : '=eventBroadcast'
},
transclude: true,
template: '<div class="angular-leaflet-map"><div ng-transclude></div></div>',
controller: ["$scope", function ($scope) {
_leafletMap = $q.defer();
this.getMap = function () {
return _leafletMap.promise;
};
this.getLeafletScope = function() {
return $scope;
};
}],
link: function(scope, element, attrs) {
var isDefined = leafletHelpers.isDefined,
defaults = leafletMapDefaults.setDefaults(scope.defaults, attrs.id),
genDispatchMapEvent = leafletEvents.genDispatchMapEvent,
mapEvents = leafletEvents.getAvailableMapEvents();
// Set width and height utility functions
function updateWidth() {
if (isNaN(attrs.width)) {
element.css('width', attrs.width);
} else {
element.css('width', attrs.width + 'px');
}
}
function updateHeight() {
if (isNaN(attrs.height)) {
element.css('height', attrs.height);
} else {
element.css('height', attrs.height + 'px');
}
}
// If the width attribute defined update css
// Then watch if bound property changes and update css
if (isDefined(attrs.width)) {
updateWidth();
scope.$watch(
function () {
return element[0].getAttribute('width');
},
function () {
updateWidth();
map.invalidateSize();
});
}
// If the height attribute defined update css
// Then watch if bound property changes and update css
if (isDefined(attrs.height)) {
updateHeight();
scope.$watch(
function () {
return element[0].getAttribute('height');
},
function () {
updateHeight();
map.invalidateSize();
});
}
// Create the Leaflet Map Object with the options
var map = new L.Map(element[0], leafletMapDefaults.getMapCreationDefaults(attrs.id));
_leafletMap.resolve(map);
if (!isDefined(attrs.center)) {
map.setView([defaults.center.lat, defaults.center.lng], defaults.center.zoom);
}
// If no layers nor tiles defined, set the default tileLayer
if (!isDefined(attrs.tiles) && (!isDefined(attrs.layers))) {
var tileLayerObj = L.tileLayer(defaults.tileLayer, defaults.tileLayerOptions);
tileLayerObj.addTo(map);
leafletData.setTiles(tileLayerObj, attrs.id);
}
// Set zoom control configuration
if (isDefined(map.zoomControl) &&
isDefined(defaults.zoomControlPosition)) {
map.zoomControl.setPosition(defaults.zoomControlPosition);
}
if (isDefined(map.zoomControl) &&
defaults.zoomControl===false) {
map.zoomControl.removeFrom(map);
}
if (isDefined(map.zoomsliderControl) &&
isDefined(defaults.zoomsliderControl) &&
defaults.zoomsliderControl===false) {
map.zoomsliderControl.removeFrom(map);
}
// if no event-broadcast attribute, all events are broadcasted
if (!isDefined(attrs.eventBroadcast)) {
var logic = "broadcast";
for (var i = 0; i < mapEvents.length; i++) {
var eventName = mapEvents[i];
map.on(eventName, genDispatchMapEvent(scope, eventName, logic), {
eventName: eventName
});
}
}
// Resolve the map object to the promises
map.whenReady(function() {
leafletData.setMap(map, attrs.id);
});
scope.$on('$destroy', function () {
try {
map.remove();
leafletData.unresolveMap(attrs.id);
} catch (e) {
}
});
//Handle request to invalidate the map size
//Up scope using $scope.$emit('invalidateSize')
//Down scope using $scope.$broadcast('invalidateSize')
scope.$on('invalidateSize', function() {
map.invalidateSize();
});
}
};
}]);
angular.module("leaflet-directive").directive('center',
["$log", "$q", "$location", "$timeout", "leafletMapDefaults", "leafletHelpers", "leafletBoundsHelpers", "leafletEvents", function ($log, $q, $location, $timeout, leafletMapDefaults, leafletHelpers, leafletBoundsHelpers, leafletEvents) {
var isDefined = leafletHelpers.isDefined,
isNumber = leafletHelpers.isNumber,
isSameCenterOnMap = leafletHelpers.isSameCenterOnMap,
safeApply = leafletHelpers.safeApply,
isValidCenter = leafletHelpers.isValidCenter,
isEmpty = leafletHelpers.isEmpty,
isUndefinedOrEmpty = leafletHelpers.isUndefinedOrEmpty;
var shouldInitializeMapWithBounds = function(bounds, center) {
return (isDefined(bounds) && !isEmpty(bounds)) && isUndefinedOrEmpty(center);
};
var _leafletCenter;
return {
restrict: "A",
scope: false,
replace: false,
require: 'leaflet',
controller: function () {
_leafletCenter = $q.defer();
this.getCenter = function() {
return _leafletCenter.promise;
};
},
link: function(scope, element, attrs, controller) {
var leafletScope = controller.getLeafletScope(),
centerModel = leafletScope.center;
controller.getMap().then(function(map) {
var defaults = leafletMapDefaults.getDefaults(attrs.id);
if (attrs.center.search("-") !== -1) {
$log.error('The "center" variable can\'t use a "-" on his key name: "' + attrs.center + '".');
map.setView([defaults.center.lat, defaults.center.lng], defaults.center.zoom);
return;
} else if (shouldInitializeMapWithBounds(leafletScope.bounds, centerModel)) {
map.fitBounds(leafletBoundsHelpers.createLeafletBounds(leafletScope.bounds));
centerModel = map.getCenter();
safeApply(leafletScope, function (scope) {
scope.center = {
lat: map.getCenter().lat,
lng: map.getCenter().lng,
zoom: map.getZoom(),
autoDiscover: false
};
});
safeApply(leafletScope, function (scope) {
var mapBounds = map.getBounds();
var newScopeBounds = {
northEast: {
lat: mapBounds._northEast.lat,
lng: mapBounds._northEast.lng
},
southWest: {
lat: mapBounds._southWest.lat,
lng: mapBounds._southWest.lng
}
};
scope.bounds = newScopeBounds;
});
} else if (!isDefined(centerModel)) {
$log.error('The "center" property is not defined in the main scope');
map.setView([defaults.center.lat, defaults.center.lng], defaults.center.zoom);
return;
} else if (!(isDefined(centerModel.lat) && isDefined(centerModel.lng)) && !isDefined(centerModel.autoDiscover)) {
angular.copy(defaults.center, centerModel);
}
var urlCenterHash, mapReady;
if (attrs.urlHashCenter === "yes") {
var extractCenterFromUrl = function() {
var search = $location.search();
var centerParam;
if (isDefined(search.c)) {
var cParam = search.c.split(":");
if (cParam.length === 3) {
centerParam = { lat: parseFloat(cParam[0]), lng: parseFloat(cParam[1]), zoom: parseInt(cParam[2], 10) };
}
}
return centerParam;
};
urlCenterHash = extractCenterFromUrl();
leafletScope.$on('$locationChangeSuccess', function(event) {
var scope = event.currentScope;
//$log.debug("updated location...");
var urlCenter = extractCenterFromUrl();
if (isDefined(urlCenter) && !isSameCenterOnMap(urlCenter, map)) {
//$log.debug("updating center model...", urlCenter);
scope.center = {
lat: urlCenter.lat,
lng: urlCenter.lng,
zoom: urlCenter.zoom
};
}
});
}
leafletScope.$watch("center", function(center) {
//$log.debug("updated center model...");
// The center from the URL has priority
if (isDefined(urlCenterHash)) {
angular.copy(urlCenterHash, center);
urlCenterHash = undefined;
}
if (!isValidCenter(center) && center.autoDiscover !== true) {
$log.warn("[AngularJS - Leaflet] invalid 'center'");
//map.setView([defaults.center.lat, defaults.center.lng], defaults.center.zoom);
return;
}
if (center.autoDiscover === true) {
if (!isNumber(center.zoom)) {
map.setView([defaults.center.lat, defaults.center.lng], defaults.center.zoom);
}
if (isNumber(center.zoom) && center.zoom > defaults.center.zoom) {
map.locate({ setView: true, maxZoom: center.zoom });
} else if (isDefined(defaults.maxZoom)) {
map.locate({ setView: true, maxZoom: defaults.maxZoom });
} else {
map.locate({ setView: true });
}
return;
}
if (mapReady && isSameCenterOnMap(center, map)) {
//$log.debug("no need to update map again.");
return;
}
//$log.debug("updating map center...", center);
leafletScope.settingCenterFromScope = true;
map.setView([center.lat, center.lng], center.zoom);
leafletEvents.notifyCenterChangedToBounds(leafletScope, map);
$timeout(function() {
leafletScope.settingCenterFromScope = false;
//$log.debug("allow center scope updates");
});
}, true);
map.whenReady(function() {
mapReady = true;
});
map.on("moveend", function(/* event */) {
// Resolve the center after the first map position
_leafletCenter.resolve();
leafletEvents.notifyCenterUrlHashChanged(leafletScope, map, attrs, $location.search());
//$log.debug("updated center on map...");
if (isSameCenterOnMap(centerModel, map) || scope.settingCenterFromScope) {
//$log.debug("same center in model, no need to update again.");
return;
}
safeApply(leafletScope, function(scope) {
if (!leafletScope.settingCenterFromScope) {
//$log.debug("updating center model...", map.getCenter(), map.getZoom());
scope.center = {
lat: map.getCenter().lat,
lng: map.getCenter().lng,
zoom: map.getZoom(),
autoDiscover: false
};
}
leafletEvents.notifyCenterChangedToBounds(leafletScope, map);
});
});
if (centerModel.autoDiscover === true) {
map.on("locationerror", function() {
$log.warn("[AngularJS - Leaflet] The Geolocation API is unauthorized on this page.");
if (isValidCenter(centerModel)) {
map.setView([centerModel.lat, centerModel.lng], centerModel.zoom);
leafletEvents.notifyCenterChangedToBounds(leafletScope, map);
} else {
map.setView([defaults.center.lat, defaults.center.lng], defaults.center.zoom);
leafletEvents.notifyCenterChangedToBounds(leafletScope, map);
}
});
}
});
}
};
}]);
angular.module("leaflet-directive").directive('tiles', ["$log", "leafletData", "leafletMapDefaults", "leafletHelpers", function ($log, leafletData, leafletMapDefaults, leafletHelpers) {
return {
restrict: "A",
scope: false,
replace: false,
require: 'leaflet',
link: function(scope, element, attrs, controller) {
var isDefined = leafletHelpers.isDefined,
leafletScope = controller.getLeafletScope(),
tiles = leafletScope.tiles;
if (!isDefined(tiles) && !isDefined(tiles.url)) {
$log.warn("[AngularJS - Leaflet] The 'tiles' definition doesn't have the 'url' property.");
return;
}
controller.getMap().then(function(map) {
var defaults = leafletMapDefaults.getDefaults(attrs.id);
var tileLayerObj;
leafletScope.$watch("tiles", function(tiles) {
var tileLayerOptions = defaults.tileLayerOptions;
var tileLayerUrl = defaults.tileLayer;
// If no valid tiles are in the scope, remove the last layer
if (!isDefined(tiles.url) && isDefined(tileLayerObj)) {
map.removeLayer(tileLayerObj);
return;
}
// No leafletTiles object defined yet
if (!isDefined(tileLayerObj)) {
if (isDefined(tiles.options)) {
angular.copy(tiles.options, tileLayerOptions);
}
if (isDefined(tiles.url)) {
tileLayerUrl = tiles.url;
}
tileLayerObj = L.tileLayer(tileLayerUrl, tileLayerOptions);
tileLayerObj.addTo(map);
leafletData.setTiles(tileLayerObj, attrs.id);
return;
}
// If the options of the tilelayer is changed, we need to redraw the layer
if (isDefined(tiles.url) && isDefined(tiles.options) && !angular.equals(tiles.options, tileLayerOptions)) {
map.removeLayer(tileLayerObj);
tileLayerOptions = defaults.tileLayerOptions;
angular.copy(tiles.options, tileLayerOptions);
tileLayerUrl = tiles.url;
tileLayerObj = L.tileLayer(tileLayerUrl, tileLayerOptions);
tileLayerObj.addTo(map);
leafletData.setTiles(tileLayerObj, attrs.id);
return;
}
// Only the URL of the layer is changed, update the tiles object
if (isDefined(tiles.url)) {
tileLayerObj.setUrl(tiles.url);
}
}, true);
});
}
};
}]);
angular.module("leaflet-directive").directive('legend', ["$log", "$http", "leafletHelpers", "leafletLegendHelpers", function ($log, $http, leafletHelpers, leafletLegendHelpers) {
return {
restrict: "A",
scope: false,
replace: false,
require: 'leaflet',
link: function(scope, element, attrs, controller) {
var isArray = leafletHelpers.isArray,
isDefined = leafletHelpers.isDefined,
isFunction = leafletHelpers.isFunction,
leafletScope = controller.getLeafletScope(),
legend = leafletScope.legend;
var legendClass = legend.legendClass ? legend.legendClass : "legend";
var position = legend.position || 'bottomright';
var leafletLegend;
controller.getMap().then(function(map) {
leafletScope.$watch('legend', function (legend) {
if (!isDefined(legend.url) && (!isArray(legend.colors) || !isArray(legend.labels) || legend.colors.length !== legend.labels.length)) {
$log.warn("[AngularJS - Leaflet] legend.colors and legend.labels must be set.");
} else if(isDefined(legend.url)){
$log.info("[AngularJS - Leaflet] loading arcgis legend service.");
} else {
if (isDefined(leafletLegend)) {
leafletLegend.removeFrom(map);
}
leafletLegend = L.control({ position: position });
leafletLegend.onAdd = leafletLegendHelpers.getOnAddArrayLegend(legend, legendClass);
leafletLegend.addTo(map);
}
});
leafletScope.$watch('legend.url', function(newURL) {
if(!isDefined(newURL)) {
return;
}
$http.get(newURL)
.success(function(legendData) {
if(isDefined(leafletLegend)) {
leafletLegendHelpers.updateArcGISLegend(leafletLegend.getContainer(),legendData);
} else {
leafletLegend = L.control({ position: position });
leafletLegend.onAdd = leafletLegendHelpers.getOnAddArcGISLegend(legendData, legendClass);
leafletLegend.addTo(map);
}
if(isDefined(legend.loadedData) && isFunction(legend.loadedData)) {
legend.loadedData();
}
})
.error(function() {
$log.warn('[AngularJS - Leaflet] legend.url not loaded.');
});
});
});
}
};
}]);
angular.module("leaflet-directive").directive('geojson', ["$log", "$rootScope", "leafletData", "leafletHelpers", function ($log, $rootScope, leafletData, leafletHelpers) {
return {
restrict: "A",
scope: false,
replace: false,
require: 'leaflet',
link: function(scope, element, attrs, controller) {
var safeApply = leafletHelpers.safeApply,
isDefined = leafletHelpers.isDefined,
leafletScope = controller.getLeafletScope(),
leafletGeoJSON = {};
controller.getMap().then(function(map) {
leafletScope.$watch("geojson", function(geojson) {
if (isDefined(leafletGeoJSON) && map.hasLayer(leafletGeoJSON)) {
map.removeLayer(leafletGeoJSON);
}
if (!(isDefined(geojson) && isDefined(geojson.data))) {
return;
}
var resetStyleOnMouseout = geojson.resetStyleOnMouseout,
onEachFeature = geojson.onEachFeature;
geojson.options = {
style: geojson.style,
filter: geojson.filter,
onEachFeature: onEachFeature,
pointToLayer: geojson.pointToLayer
};
leafletGeoJSON = L.geoJson(geojson.data, geojson.options);
leafletData.setGeoJSON(leafletGeoJSON, attrs.id);
leafletGeoJSON.addTo(map);
if (!onEachFeature) {
onEachFeature = function(feature, layer) {
if (leafletHelpers.LabelPlugin.isLoaded() && isDefined(geojson.label)) {
layer.bindLabel(feature.properties.description);
}
layer.on({
mouseover: function(e) {
safeApply(leafletScope, function() {
geojson.selected = feature;
$rootScope.$broadcast('leafletDirectiveMap.geojsonMouseover', e);
});
},
mouseout: function(e) {
if (resetStyleOnMouseout) {
leafletGeoJSON.resetStyle(e.target);
}
safeApply(leafletScope, function() {
geojson.selected = undefined;
$rootScope.$broadcast('leafletDirectiveMap.geojsonMouseout', e);
});
},
click: function(e) {
safeApply(leafletScope, function() {
geojson.selected = feature;
$rootScope.$broadcast('leafletDirectiveMap.geojsonClick', geojson.selected, e);
});
}
});
};
}
}, true);
});
}
};
}]);
angular.module("leaflet-directive").directive('layers', ["$log", "$q", "leafletData", "leafletHelpers", "leafletLayerHelpers", "leafletControlHelpers", function ($log, $q, leafletData, leafletHelpers, leafletLayerHelpers, leafletControlHelpers) {
return {
restrict: "A",
scope: false,
replace: false,
require: 'leaflet',
controller: ["$scope", function ($scope) {
$scope._leafletLayers = $q.defer();
this.getLayers = function () {
return $scope._leafletLayers.promise;
};
}],
link: function(scope, element, attrs, controller){
var isDefined = leafletHelpers.isDefined,
leafletLayers = {},
leafletScope = controller.getLeafletScope(),
layers = leafletScope.layers,
createLayer = leafletLayerHelpers.createLayer,
updateLayersControl = leafletControlHelpers.updateLayersControl,
isLayersControlVisible = false;
controller.getMap().then(function(map) {
// Do we have a baselayers property?
if (!isDefined(layers) || !isDefined(layers.baselayers) || Object.keys(layers.baselayers).length === 0) {
// No baselayers property
$log.error('[AngularJS - Leaflet] At least one baselayer has to be defined');
return;
}
// We have baselayers to add to the map
scope._leafletLayers.resolve(leafletLayers);
leafletData.setLayers(leafletLayers, attrs.id);
leafletLayers.baselayers = {};
leafletLayers.overlays = {};
var mapId = attrs.id;
// Setup all baselayers definitions
var oneVisibleLayer = false;
for (var layerName in layers.baselayers) {
var newBaseLayer = createLayer(layers.baselayers[layerName]);
if (!isDefined(newBaseLayer)) {
delete layers.baselayers[layerName];
continue;
}
leafletLayers.baselayers[layerName] = newBaseLayer;
// Only add the visible layer to the map, layer control manages the addition to the map
// of layers in its control
if (layers.baselayers[layerName].top === true) {
map.addLayer(leafletLayers.baselayers[layerName]);
oneVisibleLayer = true;
}
}
// If there is no visible layer add first to the map
if (!oneVisibleLayer && Object.keys(leafletLayers.baselayers).length > 0) {
map.addLayer(leafletLayers.baselayers[Object.keys(layers.baselayers)[0]]);
}
// Setup the Overlays
for (layerName in layers.overlays) {
if(layers.overlays[layerName].type === 'cartodb') {
}
var newOverlayLayer = createLayer(layers.overlays[layerName]);
if (!isDefined(newOverlayLayer)) {
delete layers.overlays[layerName];
continue;
}
leafletLayers.overlays[layerName] = newOverlayLayer;
// Only add the visible overlays to the map
if (layers.overlays[layerName].visible === true) {
map.addLayer(leafletLayers.overlays[layerName]);
}
}
// Watch for the base layers
leafletScope.$watch('layers.baselayers', function(newBaseLayers) {
// Delete layers from the array
for (var name in leafletLayers.baselayers) {
if (!isDefined(newBaseLayers[name])) {
// Remove from the map if it's on it
if (map.hasLayer(leafletLayers.baselayers[name])) {
map.removeLayer(leafletLayers.baselayers[name]);
}
delete leafletLayers.baselayers[name];
}
}
// add new layers
for (var newName in newBaseLayers) {
if (!isDefined(leafletLayers.baselayers[newName])) {
var testBaseLayer = createLayer(newBaseLayers[newName]);
if (isDefined(testBaseLayer)) {
leafletLayers.baselayers[newName] = testBaseLayer;
// Only add the visible layer to the map
if (newBaseLayers[newName].top === true) {
map.addLayer(leafletLayers.baselayers[newName]);
}
}
}
}
if (Object.keys(leafletLayers.baselayers).length === 0) {
$log.error('[AngularJS - Leaflet] At least one baselayer has to be defined');
return;
}
//we have layers, so we need to make, at least, one active
var found = false;
// search for an active layer
for (var key in leafletLayers.baselayers) {
if (map.hasLayer(leafletLayers.baselayers[key])) {
found = true;
break;
}
}
// If there is no active layer make one active
if (!found) {
map.addLayer(leafletLayers.baselayers[Object.keys(layers.baselayers)[0]]);
}
// Only show the layers switch selector control if we have more than one baselayer + overlay
isLayersControlVisible = updateLayersControl(map, mapId, isLayersControlVisible, newBaseLayers, layers.overlays, leafletLayers);
}, true);
// Watch for the overlay layers
leafletScope.$watch('layers.overlays', function(newOverlayLayers) {
// Delete layers from the array
for (var name in leafletLayers.overlays) {
if (!isDefined(newOverlayLayers[name])) {
// Remove from the map if it's on it
if (map.hasLayer(leafletLayers.overlays[name])) {
map.removeLayer(leafletLayers.overlays[name]);
}
// TODO: Depending on the layer type we will have to delete what's included on it
delete leafletLayers.overlays[name];
}
}
// add new overlays
for (var newName in newOverlayLayers) {
if (!isDefined(leafletLayers.overlays[newName])) {
var testOverlayLayer = createLayer(newOverlayLayers[newName]);
if (isDefined(testOverlayLayer)) {
leafletLayers.overlays[newName] = testOverlayLayer;
if (newOverlayLayers[newName].visible === true) {
map.addLayer(leafletLayers.overlays[newName]);
}
}
}
// check for the .visible property to hide/show overLayers
if (newOverlayLayers[newName].visible && !map.hasLayer(leafletLayers.overlays[newName])) {
map.addLayer(leafletLayers.overlays[newName]);
} else if (newOverlayLayers[newName].visible === false && map.hasLayer(leafletLayers.overlays[newName])) {
map.removeLayer(leafletLayers.overlays[newName]);
}
}
// Only add the layers switch selector control if we have more than one baselayer + overlay
isLayersControlVisible = updateLayersControl(map, mapId, isLayersControlVisible, layers.baselayers, newOverlayLayers, leafletLayers);
}, true);
});
}
};
}]);
angular.module("leaflet-directive").directive('bounds', ["$log", "$timeout", "leafletHelpers", "leafletBoundsHelpers", function ($log, $timeout, leafletHelpers, leafletBoundsHelpers) {
return {
restrict: "A",
scope: false,
replace: false,
require: [ 'leaflet', 'center' ],
link: function(scope, element, attrs, controller) {
var isDefined = leafletHelpers.isDefined,
createLeafletBounds = leafletBoundsHelpers.createLeafletBounds,
leafletScope = controller[0].getLeafletScope(),
mapController = controller[0];
var emptyBounds = function(bounds) {
if (bounds._southWest.lat === 0 && bounds._southWest.lng === 0 && bounds._northEast.lat === 0 && bounds._northEast.lng === 0) {
return true;
}
return false;
};
mapController.getMap().then(function (map) {
leafletScope.$on('boundsChanged', function (event) {
var scope = event.currentScope;
var bounds = map.getBounds();
//$log.debug('updated map bounds...', bounds);
if (emptyBounds(bounds) || scope.settingBoundsFromScope) {
return;
}
var newScopeBounds = {
northEast: {
lat: bounds._northEast.lat,
lng: bounds._northEast.lng
},
southWest: {
lat: bounds._southWest.lat,
lng: bounds._southWest.lng
}
};
if (!angular.equals(scope.bounds, newScopeBounds)) {
//$log.debug('Need to update scope bounds.');
scope.bounds = newScopeBounds;
}
});
leafletScope.$watch('bounds', function (bounds) {
//$log.debug('updated bounds...', bounds);
if (!isDefined(bounds)) {
$log.error('[AngularJS - Leaflet] Invalid bounds');
return;
}
var leafletBounds = createLeafletBounds(bounds);
if (leafletBounds && !map.getBounds().equals(leafletBounds)) {
//$log.debug('Need to update map bounds.');
scope.settingBoundsFromScope = true;
map.fitBounds(leafletBounds);
$timeout( function() {
//$log.debug('Allow bound updates.');
scope.settingBoundsFromScope = false;
});
}
}, true);
});
}
};
}]);
angular.module("leaflet-directive").directive('markers', ["$log", "$rootScope", "$q", "leafletData", "leafletHelpers", "leafletMapDefaults", "leafletMarkersHelpers", "leafletEvents", function ($log, $rootScope, $q, leafletData, leafletHelpers, leafletMapDefaults, leafletMarkersHelpers, leafletEvents) {
return {
restrict: "A",
scope: false,
replace: false,
require: ['leaflet', '?layers'],
link: function(scope, element, attrs, controller) {
var mapController = controller[0],
Helpers = leafletHelpers,
isDefined = leafletHelpers.isDefined,
isString = leafletHelpers.isString,
leafletScope = mapController.getLeafletScope(),
deleteMarker = leafletMarkersHelpers.deleteMarker,
addMarkerWatcher = leafletMarkersHelpers.addMarkerWatcher,
listenMarkerEvents = leafletMarkersHelpers.listenMarkerEvents,
addMarkerToGroup = leafletMarkersHelpers.addMarkerToGroup,
bindMarkerEvents = leafletEvents.bindMarkerEvents,
createMarker = leafletMarkersHelpers.createMarker;
mapController.getMap().then(function(map) {
var leafletMarkers = {},
getLayers;
// If the layers attribute is used, we must wait until the layers are created
if (isDefined(controller[1])) {
getLayers = controller[1].getLayers;
} else {
getLayers = function() {
var deferred = $q.defer();
deferred.resolve();
return deferred.promise;
};
}
getLayers().then(function(layers) {
leafletData.setMarkers(leafletMarkers, attrs.id);
leafletScope.$watch('markers', function(newMarkers) {
// Delete markers from the array
for (var name in leafletMarkers) {
if (!isDefined(newMarkers) || !isDefined(newMarkers[name])) {
deleteMarker(leafletMarkers[name], map, layers);
delete leafletMarkers[name];
}
}
// add new markers
for (var newName in newMarkers) {
if (newName.search("-") !== -1) {
$log.error('The marker can\'t use a "-" on his key name: "' + newName + '".');
continue;
}
if (!isDefined(leafletMarkers[newName])) {
var markerData = newMarkers[newName];
var marker = createMarker(markerData);
if (!isDefined(marker)) {
$log.error('[AngularJS - Leaflet] Received invalid data on the marker ' + newName + '.');
continue;
}
leafletMarkers[newName] = marker;
// Bind message
if (isDefined(markerData.message)) {
marker.bindPopup(markerData.message, markerData.popupOptions);
}
// Add the marker to a cluster group if needed
if (isDefined(markerData.group)) {
var groupOptions = isDefined(markerData.groupOption) ? markerData.groupOption : null;
addMarkerToGroup(marker, markerData.group, groupOptions, map);
}
// Show label if defined
if (Helpers.LabelPlugin.isLoaded() && isDefined(markerData.label) && isDefined(markerData.label.message)) {
marker.bindLabel(markerData.label.message, markerData.label.options);
}
// Check if the marker should be added to a layer
if (isDefined(markerData) && isDefined(markerData.layer)) {
if (!isString(markerData.layer)) {
$log.error('[AngularJS - Leaflet] A layername must be a string');
continue;
}
if (!isDefined(layers)) {
$log.error('[AngularJS - Leaflet] You must add layers to the directive if the markers are going to use this functionality.');
continue;
}
if (!isDefined(layers.overlays) || !isDefined(layers.overlays[markerData.layer])) {
$log.error('[AngularJS - Leaflet] A marker can only be added to a layer of type "group"');
continue;
}
var layerGroup = layers.overlays[markerData.layer];
if (!(layerGroup instanceof L.LayerGroup || layerGroup instanceof L.FeatureGroup)) {
$log.error('[AngularJS - Leaflet] Adding a marker to an overlay needs a overlay of the type "group" or "featureGroup"');
continue;
}
// The marker goes to a correct layer group, so first of all we add it
layerGroup.addLayer(marker);
// The marker is automatically added to the map depending on the visibility
// of the layer, so we only have to open the popup if the marker is in the map
if (map.hasLayer(marker) && markerData.focus === true) {
marker.openPopup();
}
// Add the marker to the map if it hasn't been added to a layer or to a group
} else if (!isDefined(markerData.group)) {
// We do not have a layer attr, so the marker goes to the map layer
map.addLayer(marker);
if (markerData.focus === true) {
marker.openPopup();
}
if (Helpers.LabelPlugin.isLoaded() && isDefined(markerData.label) && isDefined(markerData.label.options) && markerData.label.options.noHide === true) {
marker.showLabel();
}
}
// Should we watch for every specific marker on the map?
var shouldWatch = (!isDefined(attrs.watchMarkers) || attrs.watchMarkers === 'true');
if (shouldWatch) {
addMarkerWatcher(marker, newName, leafletScope, layers, map);
listenMarkerEvents(marker, markerData, leafletScope);
}
bindMarkerEvents(marker, newName, markerData, leafletScope);
}
}
}, true);
});
});
}
};
}]);
angular.module("leaflet-directive").directive('paths', ["$log", "$q", "leafletData", "leafletMapDefaults", "leafletHelpers", "leafletPathsHelpers", "leafletEvents", function ($log, $q, leafletData, leafletMapDefaults, leafletHelpers, leafletPathsHelpers, leafletEvents) {
return {
restrict: "A",
scope: false,
replace: false,
require: ['leaflet', '?layers'],
link: function(scope, element, attrs, controller) {
var mapController = controller[0],
isDefined = leafletHelpers.isDefined,
isString = leafletHelpers.isString,
leafletScope = mapController.getLeafletScope(),
paths = leafletScope.paths,
createPath = leafletPathsHelpers.createPath,
bindPathEvents = leafletEvents.bindPathEvents,
setPathOptions = leafletPathsHelpers.setPathOptions;
mapController.getMap().then(function(map) {
var defaults = leafletMapDefaults.getDefaults(attrs.id),
getLayers;
// If the layers attribute is used, we must wait until the layers are created
if (isDefined(controller[1])) {
getLayers = controller[1].getLayers;
} else {
getLayers = function() {
var deferred = $q.defer();
deferred.resolve();
return deferred.promise;
};
}
if (!isDefined(paths)) {
return;
}
getLayers().then(function(layers) {
var leafletPaths = {};
leafletData.setPaths(leafletPaths, attrs.id);
// Function for listening every single path once created
var watchPathFn = function(leafletPath, name) {
var clearWatch = leafletScope.$watch('paths.' + name, function(pathData) {
if (!isDefined(pathData)) {
map.removeLayer(leafletPath);
clearWatch();
return;
}
setPathOptions(leafletPath, pathData.type, pathData);
}, true);
};
leafletScope.$watch("paths", function (newPaths) {
// Create the new paths
for (var newName in newPaths) {
if (newName.search('\\$') === 0) {
continue;
}
if (newName.search("-") !== -1) {
$log.error('[AngularJS - Leaflet] The path name "' + newName + '" is not valid. It must not include "-" and a number.');
continue;
}
if (!isDefined(leafletPaths[newName])) {
var pathData = newPaths[newName];
var newPath = createPath(newName, newPaths[newName], defaults);
// bind popup if defined
if (isDefined(newPath) && isDefined(pathData.message)) {
newPath.bindPopup(pathData.message);
}
// Show label if defined
if (leafletHelpers.LabelPlugin.isLoaded() && isDefined(pathData.label) && isDefined(pathData.label.message)) {
newPath.bindLabel(pathData.label.message, pathData.label.options);
}
// Check if the marker should be added to a layer
if (isDefined(pathData) && isDefined(pathData.layer)) {
if (!isString(pathData.layer)) {