From 99fe9ec76f92f766f41f735c424f2962e89aaf16 Mon Sep 17 00:00:00 2001 From: GabrielKS <23368820+GabrielKS@users.noreply.github.com> Date: Fri, 20 Aug 2021 14:17:41 -0700 Subject: [PATCH 001/175] Try to fix the new Label UI walkthrough bug See https://github.com/e-mission/e-mission-docs/issues/669. This should hopefully be a fix, but the problem occurs so inconsistently that I can't be sure. Steps taken: + Select walkthrough targets by ID + Remove incorrect use of IDs to make room for correct use of IDs + Use mildly hacky CSS to exclude DOM elements that have been translated to negative X, which often happens with the duplicated ones + Scroll back down only at the end of the walkthrough so we can back to the previous step more often + Fix walkthrough launch button padding Testing done: + Tested on an emulated iPhone 8 logged in with my real stage token - I had previously often been able to reproduce the problem under these conditions, and now I'm not seeing the problem, but it could just happen to not be appearing --- www/css/main.diary.css | 1 - www/css/style.css | 2 +- www/js/diary/infinite_scroll_list.js | 162 ++++++++++-------- www/templates/control/main-control.html | 16 +- www/templates/diary/infinite_scroll_list.html | 9 +- www/templates/diary/list.html | 2 +- 6 files changed, 107 insertions(+), 85 deletions(-) diff --git a/www/css/main.diary.css b/www/css/main.diary.css index b925f4657..cc0f33317 100644 --- a/www/css/main.diary.css +++ b/www/css/main.diary.css @@ -180,7 +180,6 @@ div.labelfilterlist { } .labelfilter:first-of-type { - margin-left:5%; border-top-left-radius: 5px; border-bottom-left-radius: 5px; } diff --git a/www/css/style.css b/www/css/style.css index 8e4196e0d..dee871077 100644 --- a/www/css/style.css +++ b/www/css/style.css @@ -695,7 +695,7 @@ background-image: none !important; } background-color: #E0A1A1 !important; } -#gray.control-icon-button{ +.gray-icon.control-icon-button{ background-color: #CCCCCC !important; } diff --git a/www/js/diary/infinite_scroll_list.js b/www/js/diary/infinite_scroll_list.js index de60ab8a8..8291e11ed 100644 --- a/www/js/diary/infinite_scroll_list.js +++ b/www/js/diary/infinite_scroll_list.js @@ -45,6 +45,10 @@ angular.module('emission.main.diary.infscrolllist',['ui-leaflet', $scope.data = {}; + // To aid in the walkthrough fix (see https://github.com/e-mission/e-mission-docs/issues/669) + var firstTripID = ""; + $scope.getMoreTripsID = 'walkthrough'+'-'+'getmoretrips'; + $scope.getActiveFilters = function() { return $scope.filterInputs.filter(sf => sf.state).map(sf => sf.key); } @@ -247,6 +251,7 @@ angular.module('emission.main.diary.infscrolllist',['ui-leaflet', if (!alreadyFiltered) { $scope.data.displayTrips = $scope.data.allTrips; }; + firstTripID = "diary-card-"+$scope.data.displayTrips[0].dom_id; } angular.extend($scope, { @@ -485,6 +490,7 @@ angular.module('emission.main.diary.infscrolllist',['ui-leaflet', // Pre-populate start and end names with   so they take up the same amount of vertical space in the UI before they are populated with real data tripgj.start_display_name = "\xa0"; tripgj.end_display_name = "\xa0"; + tripgj.dom_id = Math.round(tripgj.start_ts).toString(); } const fillPlacesForTripAsync = function(tripgj) { @@ -601,81 +607,97 @@ angular.module('emission.main.diary.infscrolllist',['ui-leaflet', }; // Tour steps - var tour = { - config: { - mask: { - visibleOnNoTarget: true, - clickExit: true, + var tour = function() { + // We do some extra work here to avoid trying to target DOM elements that have been duplicated and moved off-screen. See https://github.com/e-mission/e-mission-docs/issues/669. + // filterOutTopLeft helps us ignore duplicated DOM elements that get translate3d'd to -9999, -9999, 0: + const filterOutTopLeft = ":not([style*='transform: translate3d(-'])"; + // tripTag filters out duplicated DOM elements using the above, then gets the first trip by time. This is necessary because the trips are not necessarily in order in the DOM even though they appear in order on the screen. + const tripTag = ".collection-repeat-container>div"+filterOutTopLeft+" #"+firstTripID+" "; + // The "load more trips" button sometimes has the glitchy behavior as well. I haven't been able to reproduce enough to narrow down the issue; for now, we'll try the same tricks as we try with the trips. + const loadMoreTag = ".scroll"+filterOutTopLeft+" .control-icon-button#"+$scope.getMoreTripsID; + return { + config: { + mask: { + visibleOnNoTarget: true, + clickExit: true, + }, + previousText: $translate.instant('tour-previous'), + nextText: $translate.instant('tour-next'), + finishText: $translate.instant('tour-finish') }, - previousText: $translate.instant('tour-previous'), - nextText: $translate.instant('tour-next'), - finishText: $translate.instant('tour-finish') - }, - steps: [{ - target: '.ion-view-background', - content: $translate.instant('new_label_tour.0') - }, - { - target: '.labelfilter', - content: $translate.instant('new_label_tour.1') - }, - { - target: '.labelfilter.last', - content: $translate.instant('new_label_tour.2') - }, - { - target: '.diary-entry', - content: $translate.instant('new_label_tour.3') - }, - { - target: '.control-icon-button', - content: $translate.instant('new_label_tour.4'), - before: function() { - return new Promise(function(resolve, reject) { - $ionicScrollDelegate.scrollTop(true); - resolve(); - }); - } - }, - { - target: '.input-confirm-row', - content: $translate.instant('new_label_tour.5') - }, - { - target: '.input-confirm-row', - content: $translate.instant('new_label_tour.6') - }, - { - target: '.diary-checkmark-container i', - content: $translate.instant('new_label_tour.7') - }, - { - target: '.input-confirm-row', - content: $translate.instant('new_label_tour.8'), - after: function() { - return new Promise(function(resolve, reject) { - $ionicScrollDelegate.scrollBottom(true); - resolve(); - }); + steps: [{ + target: '.ion-view-background', + content: $translate.instant('new_label_tour.0') + }, + { + target: '.labelfilter', + content: $translate.instant('new_label_tour.1') + }, + { + target: '.labelfilter.last', + content: $translate.instant('new_label_tour.2') + }, + { + target: '.diary-entry', + content: $translate.instant('new_label_tour.3') + }, + { + target: loadMoreTag, + content: $translate.instant('new_label_tour.4'), + before: function() { + return new Promise(function(resolve, reject) { + $ionicScrollDelegate.scrollTop(true); + resolve(); + }); + } + }, + { + target: tripTag+'.input-confirm-row', + content: $translate.instant('new_label_tour.5'), + before: function() { + return new Promise(function(resolve, reject) { + console.log("HII"); + console.log("#"+firstTripID+' .input-confirm-row'); + resolve(); + }); + } + }, + { + target: tripTag+'.input-confirm-row', + content: $translate.instant('new_label_tour.6') + }, + { + target: tripTag+'.diary-checkmark-container i', + content: $translate.instant('new_label_tour.7') + }, + { + target: tripTag+'.input-confirm-row', + content: $translate.instant('new_label_tour.8') + }, + { + target: '.labelfilter', + content: $translate.instant('new_label_tour.9') + }, + { + target: '.ion-view-background', + content: $translate.instant('new_label_tour.10') + }, + { + target: '.walkthrough-button', + content: $translate.instant('new_label_tour.11'), + after: function() { + return new Promise(function(resolve, reject) { + $ionicScrollDelegate.scrollBottom(true); + resolve(); + }); + } } - }, - { - target: '.labelfilter', - content: $translate.instant('new_label_tour.9') - }, - { - target: '.ion-view-background', - content: $translate.instant('new_label_tour.10') - }, - { - target: '.walkthrough-button', - content: $translate.instant('new_label_tour.11') - } - ] + ] + }; }; var startWalkthrough = function () { - nzTour.start(tour).then(function(result) { + nzTour.start(tour()).then(function(result) { // $ionicScrollDelegate.scrollBottom(); Logger.log("list walkthrough start completed, no error"); }).catch(function(err) { diff --git a/www/templates/control/main-control.html b/www/templates/control/main-control.html index 80a207e83..f5ff13c98 100644 --- a/www/templates/control/main-control.html +++ b/www/templates/control/main-control.html @@ -78,7 +78,7 @@
{{'.erase-data'}}
-
+
@@ -129,23 +129,23 @@
{{parseState(settings.collect.state)}}
-
+
{{'.check-log'}}
-
+
{{'.check-sensed-data'}}
-
+
{{'.check-map'}}
-
+
{{'.collection'}}
-
+
@@ -157,7 +157,7 @@
{{'.sync'}}
-
+
@@ -172,7 +172,7 @@
{{'.transition-notify'}}
-
+
diff --git a/www/templates/diary/infinite_scroll_list.html b/www/templates/diary/infinite_scroll_list.html index 436e13e5d..6ce43d429 100644 --- a/www/templates/diary/infinite_scroll_list.html +++ b/www/templates/diary/infinite_scroll_list.html @@ -2,7 +2,7 @@ - +
-
-
+ +
+
@@ -54,7 +55,7 @@

{{'diary.scroll-to-load-more' | transla
-
+
diff --git a/www/templates/diary/list.html b/www/templates/diary/list.html index ff35b962c..a20efbfa4 100644 --- a/www/templates/diary/list.html +++ b/www/templates/diary/list.html @@ -20,7 +20,7 @@ From 62da14ca82d8f0eebb334acb6826b18b868d0ccd Mon Sep 17 00:00:00 2001 From: Shankari Date: Tue, 21 Sep 2021 18:03:14 -0700 Subject: [PATCH 002/175] Try to fix the walkthrough again Albeit in a lamer fashion. The problem is that there are multiple elements with the same ID in the list. We could consider switching to a more sophisticated walkthrough solution. However, for now, we just step out to the full list of trips instead of highlighting individual items. This seems to work pretty reliably, let's push it to staging and see if it works. --- www/js/diary/infinite_scroll_list.js | 162 ++++++++---------- www/templates/diary/infinite_scroll_list.html | 9 +- 2 files changed, 74 insertions(+), 97 deletions(-) diff --git a/www/js/diary/infinite_scroll_list.js b/www/js/diary/infinite_scroll_list.js index 8291e11ed..cfbf302f9 100644 --- a/www/js/diary/infinite_scroll_list.js +++ b/www/js/diary/infinite_scroll_list.js @@ -45,10 +45,6 @@ angular.module('emission.main.diary.infscrolllist',['ui-leaflet', $scope.data = {}; - // To aid in the walkthrough fix (see https://github.com/e-mission/e-mission-docs/issues/669) - var firstTripID = ""; - $scope.getMoreTripsID = 'walkthrough'+'-'+'getmoretrips'; - $scope.getActiveFilters = function() { return $scope.filterInputs.filter(sf => sf.state).map(sf => sf.key); } @@ -251,7 +247,6 @@ angular.module('emission.main.diary.infscrolllist',['ui-leaflet', if (!alreadyFiltered) { $scope.data.displayTrips = $scope.data.allTrips; }; - firstTripID = "diary-card-"+$scope.data.displayTrips[0].dom_id; } angular.extend($scope, { @@ -490,7 +485,6 @@ angular.module('emission.main.diary.infscrolllist',['ui-leaflet', // Pre-populate start and end names with   so they take up the same amount of vertical space in the UI before they are populated with real data tripgj.start_display_name = "\xa0"; tripgj.end_display_name = "\xa0"; - tripgj.dom_id = Math.round(tripgj.start_ts).toString(); } const fillPlacesForTripAsync = function(tripgj) { @@ -607,97 +601,81 @@ angular.module('emission.main.diary.infscrolllist',['ui-leaflet', }; // Tour steps - var tour = function() { - // We do some extra work here to avoid trying to target DOM elements that have been duplicated and moved off-screen. See https://github.com/e-mission/e-mission-docs/issues/669. - // filterOutTopLeft helps us ignore duplicated DOM elements that get translate3d'd to -9999, -9999, 0: - const filterOutTopLeft = ":not([style*='transform: translate3d(-'])"; - // tripTag filters out duplicated DOM elements using the above, then gets the first trip by time. This is necessary because the trips are not necessarily in order in the DOM even though they appear in order on the screen. - const tripTag = ".collection-repeat-container>div"+filterOutTopLeft+" #"+firstTripID+" "; - // The "load more trips" button sometimes has the glitchy behavior as well. I haven't been able to reproduce enough to narrow down the issue; for now, we'll try the same tricks as we try with the trips. - const loadMoreTag = ".scroll"+filterOutTopLeft+" .control-icon-button#"+$scope.getMoreTripsID; - return { - config: { - mask: { - visibleOnNoTarget: true, - clickExit: true, - }, - previousText: $translate.instant('tour-previous'), - nextText: $translate.instant('tour-next'), - finishText: $translate.instant('tour-finish') - }, - steps: [{ - target: '.ion-view-background', - content: $translate.instant('new_label_tour.0') - }, - { - target: '.labelfilter', - content: $translate.instant('new_label_tour.1') - }, - { - target: '.labelfilter.last', - content: $translate.instant('new_label_tour.2') - }, - { - target: '.diary-entry', - content: $translate.instant('new_label_tour.3') - }, - { - target: loadMoreTag, - content: $translate.instant('new_label_tour.4'), - before: function() { - return new Promise(function(resolve, reject) { - $ionicScrollDelegate.scrollTop(true); - resolve(); - }); - } - }, - { - target: tripTag+'.input-confirm-row', - content: $translate.instant('new_label_tour.5'), - before: function() { - return new Promise(function(resolve, reject) { - console.log("HII"); - console.log("#"+firstTripID+' .input-confirm-row'); - resolve(); - }); - } + var tour = { + config: { + mask: { + visibleOnNoTarget: true, + clickExit: true, }, - { - target: tripTag+'.input-confirm-row', - content: $translate.instant('new_label_tour.6') - }, - { - target: tripTag+'.diary-checkmark-container i', - content: $translate.instant('new_label_tour.7') - }, - { - target: tripTag+'.input-confirm-row', - content: $translate.instant('new_label_tour.8') - }, - { - target: '.labelfilter', - content: $translate.instant('new_label_tour.9') - }, - { - target: '.ion-view-background', - content: $translate.instant('new_label_tour.10') - }, - { - target: '.walkthrough-button', - content: $translate.instant('new_label_tour.11'), - after: function() { - return new Promise(function(resolve, reject) { - $ionicScrollDelegate.scrollBottom(true); - resolve(); - }); - } + previousText: $translate.instant('tour-previous'), + nextText: $translate.instant('tour-next'), + finishText: $translate.instant('tour-finish') + }, + steps: [{ + target: '.ion-view-background', + content: $translate.instant('new_label_tour.0') + }, + { + target: '.labelfilter', + content: $translate.instant('new_label_tour.1') + }, + { + target: '.labelfilter.last', + content: $translate.instant('new_label_tour.2') + }, + { + target: '.diary-entry', + content: $translate.instant('new_label_tour.3') + }, + { + target: '.control-icon-button', + content: $translate.instant('new_label_tour.4'), + before: function() { + return new Promise(function(resolve, reject) { + $ionicScrollDelegate.scrollTop(true); + resolve(); + }); } - ] - }; + }, + { + target: '.diary-entry', + content: $translate.instant('new_label_tour.5') + }, + { + target: '.diary-entry', + content: $translate.instant('new_label_tour.6') + }, + { + target: '.diary-entry', + content: $translate.instant('new_label_tour.7') + }, + { + target: '.diary-entry', + content: $translate.instant('new_label_tour.8'), + after: function() { + return new Promise(function(resolve, reject) { + $ionicScrollDelegate.scrollBottom(true); + resolve(); + }); + } + }, + { + target: '.labelfilter', + content: $translate.instant('new_label_tour.9') + }, + { + target: '.ion-view-background', + content: $translate.instant('new_label_tour.10') + }, + { + target: '.walkthrough-button', + content: $translate.instant('new_label_tour.11') + } + ] }; var startWalkthrough = function () { - nzTour.start(tour()).then(function(result) { + nzTour.start(tour).then(function(result) { // $ionicScrollDelegate.scrollBottom(); Logger.log("list walkthrough start completed, no error"); }).catch(function(err) { diff --git a/www/templates/diary/infinite_scroll_list.html b/www/templates/diary/infinite_scroll_list.html index 6ce43d429..436e13e5d 100644 --- a/www/templates/diary/infinite_scroll_list.html +++ b/www/templates/diary/infinite_scroll_list.html @@ -2,7 +2,7 @@ - +
- -
-
+
+
@@ -55,7 +54,7 @@

{{'diary.scroll-to-load-more' | transla
-
+
From 9a6bd267b60c77f65378b70e203483013a5811c9 Mon Sep 17 00:00:00 2001 From: Shankari Date: Sun, 26 Sep 2021 17:15:37 -0700 Subject: [PATCH 003/175] Create a very simple directive and include it in the list view Testing done: - Load data for 2016-08-04 - Visit the day in the UI - verify that the `` element is rendered ``` inputs are ["mode","purpose"] ``` --- www/index.html | 1 + www/js/diary/list.js | 1 + www/templates/diary/list.html | 3 +++ 3 files changed, 5 insertions(+) diff --git a/www/index.html b/www/index.html index ccf0a0333..e242f95ec 100644 --- a/www/index.html +++ b/www/index.html @@ -82,6 +82,7 @@ + diff --git a/www/js/diary/list.js b/www/js/diary/list.js index 6045054e4..faf781cd0 100644 --- a/www/js/diary/list.js +++ b/www/js/diary/list.js @@ -13,6 +13,7 @@ angular.module('emission.main.diary.list',['ui-leaflet', 'emission.main.common.services', 'emission.incident.posttrip.manual', 'emission.tripconfirm.services', + 'emission.tripconfirm.multilabel', 'emission.services', 'ng-walkthrough', 'nzTour', 'emission.plugin.kvstore', 'emission.plugin.logger' diff --git a/www/templates/diary/list.html b/www/templates/diary/list.html index a20efbfa4..ecb17c605 100644 --- a/www/templates/diary/list.html +++ b/www/templates/diary/list.html @@ -86,6 +86,9 @@
+
+ +
{{input.labeltext}} From 89da98fb0601edf8516ba98919db0df59f3e768a Mon Sep 17 00:00:00 2001 From: Shankari Date: Mon, 27 Sep 2021 05:32:13 -0700 Subject: [PATCH 004/175] Have the directive include the actual functionality instead of a placeholder Move out the HTML for the button bar into "multi-label-ui.html" Move out the controller code to manipulate the popup and save the resulting data Add a new input for the list of valid labels since the code currently resets the list ``` $scope.inputParams = {} ``` so we want to do that at the screen level, and not the individual directive level. Next steps: - Figure out how to properly refactor the remaining references to ConfirmHelper.INPUTS, notably related to: - `$scope.$on('$ionicView.loaded', function() {` and - `$scope.populateInputFromTimeline(` --- www/js/diary/list.js | 105 +----------------- www/templates/diary/list.html | 23 +--- www/templates/tripconfirm/multi-label-ui.html | 22 ++++ 3 files changed, 27 insertions(+), 123 deletions(-) create mode 100644 www/templates/tripconfirm/multi-label-ui.html diff --git a/www/js/diary/list.js b/www/js/diary/list.js index faf781cd0..0d57dce3f 100644 --- a/www/js/diary/list.js +++ b/www/js/diary/list.js @@ -34,13 +34,6 @@ angular.module('emission.main.diary.list',['ui-leaflet', data.leafletObject.invalidateSize(); }); - $scope.userInputDetails = []; - ConfirmHelper.INPUTS.forEach(function(item, index) { - const currInput = angular.copy(ConfirmHelper.inputDetails[item]); - currInput.name = item; - $scope.userInputDetails.push(currInput); - }); - var readAndUpdateForDay = function(day) { // This just launches the update. The update can complete in the background // based on the time when the database finishes reading. @@ -458,110 +451,18 @@ angular.module('emission.main.diary.list',['ui-leaflet', $scope.showModes = DiaryHelper.showModes; - $scope.popovers = {}; - ConfirmHelper.INPUTS.forEach(function(item, index) { - let popoverPath = 'templates/diary/'+item.toLowerCase()+'-popover.html'; - return $ionicPopover.fromTemplateUrl(popoverPath, { - scope: $scope - }).then(function (popover) { - $scope.popovers[item] = popover; - }); - }); - - $scope.openPopover = function ($event, tripgj, inputType) { - var userInput = tripgj.userInput[inputType]; - if (angular.isDefined(userInput)) { - $scope.selected[inputType].value = userInput.value; - } else { - $scope.selected[inputType].value = ''; - } - $scope.draftInput = { - "start_ts": tripgj.data.properties.start_ts, - "end_ts": tripgj.data.properties.end_ts - }; - $scope.editingTrip = tripgj; - Logger.log("in openPopover, setting draftInput = " + JSON.stringify($scope.draftInput)); - $scope.popovers[inputType].show($event); - }; - - var closePopover = function (inputType) { - $scope.selected[inputType] = { - value: '' - }; - $scope.popovers[inputType].hide(); - }; - - /** - * Store selected value for options - * $scope.selected is for display only - * the value is displayed on popover selected option - */ - $scope.selected = {} - ConfirmHelper.INPUTS.forEach(function(item, index) { - $scope.selected[item] = {value: ''}; - }); - $scope.selected.other = {text: '', value: ''}; - - /* - * This is a curried function that curries the `$scope` variable - * while returing a function that takes `e` as the input - */ - var checkOtherOptionOnTap = function ($scope, inputType) { - return function (e) { - if (!$scope.selected.other.text) { - e.preventDefault(); - } else { - Logger.log("in choose other, other = " + JSON.stringify($scope.selected)); - $scope.store(inputType, $scope.selected.other, true /* isOther */); - $scope.selected.other = ''; - return $scope.selected.other; - } - } - }; - - $scope.choose = function (inputType) { - var isOther = false - if ($scope.selected[inputType].value != "other") { - $scope.store(inputType, $scope.selected[inputType], isOther); - } else { - isOther = true - ConfirmHelper.checkOtherOption(inputType, checkOtherOptionOnTap, $scope); - } - closePopover(inputType); - }; - + console.log('registering loaded callback'); $scope.$on('$ionicView.loaded', function() { + console.log('ionic view loaded event invoked'); $scope.inputParams = {} ConfirmHelper.INPUTS.forEach(function(item) { ConfirmHelper.getOptionsAndMaps(item).then(function(omObj) { $scope.inputParams[item] = omObj; }); }); + console.log("after loading, inputParams = "+JSON.stringify($scope.inputParams)); }); - $scope.store = function (inputType, input, isOther) { - if(isOther) { - // Let's make the value for user entered inputs look consistent with our - // other values - input.value = ConfirmHelper.otherTextToValue(input.text); - } - $scope.draftInput.label = input.value; - Logger.log("in storeInput, after setting input.value = " + input.value + ", draftInput = " + JSON.stringify($scope.draftInput)); - var tripToUpdate = $scope.editingTrip; - $window.cordova.plugins.BEMUserCache.putMessage(ConfirmHelper.inputDetails[inputType].key, $scope.draftInput).then(function () { - $scope.$apply(function() { - if (isOther) { - tripToUpdate.userInput[inputType] = ConfirmHelper.getFakeEntry(input.value); - $scope.inputParams[inputType].options.push(tripToUpdate.userInput[inputType]); - $scope.inputParams[inputType].value2entry[input.value] = tripToUpdate.userInput[inputType]; - } else { - tripToUpdate.userInput[inputType] = $scope.inputParams[inputType].value2entry[input.value]; - } - }); - }); - if (isOther == true) - $scope.draftInput = angular.undefined; - } $scope.redirect = function(){ $state.go("root.main.current"); diff --git a/www/templates/diary/list.html b/www/templates/diary/list.html index ecb17c605..8c107bf30 100644 --- a/www/templates/diary/list.html +++ b/www/templates/diary/list.html @@ -87,33 +87,14 @@
- +
-
-
- {{input.labeltext}} -
-
-
-
-
- -
-
- -
-
-
{{tripgj.display_end_time}}
-

+
diff --git a/www/templates/tripconfirm/multi-label-ui.html b/www/templates/tripconfirm/multi-label-ui.html new file mode 100644 index 000000000..b579a54a1 --- /dev/null +++ b/www/templates/tripconfirm/multi-label-ui.html @@ -0,0 +1,22 @@ + +
+
+ {{input.labeltext}} +
+
+ +
+
+
+ +
+ +
+ +
+
+
From 94d1dc96e428b34d366ac454c44be52e4f7a7890 Mon Sep 17 00:00:00 2001 From: Shankari Date: Mon, 27 Sep 2021 14:02:12 -0700 Subject: [PATCH 005/175] Add a "next" pointer to each trip MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit + To allow us to move user input labeling into the directive as well (https://github.com/e-mission/e-mission-docs/issues/674#issuecomment-928177084) This was a little tricky because it turns out that when the directive is created, `tripgj` is undefined. It then gets updated through the digest process. The really weird thing is that when we log the `scope` object directly, it looks like it also gets updated with the digest. So we ended up with logs like ``` Scope isolateBindings: {inputs: {…}, tripgj: {…}, unifiedConfirmsResults: {…}, inputParams: {…}} inputParams: {MODE: {…}, PURPOSE: {…}} inputs: (2) ["MODE", "PURPOSE"] tripgj: {data: {…}, start_place: {…}, style: ƒ, onEachFeature: ƒ, pointToLayer: ƒ, …} unifiedConfirmsResults: {MODE: Array(60), PURPOSE: Array(63)} userInputDetails: (2) [{…}, {…}]__proto__: Object unifiedresults [object Object] scope trip information is undefined ``` which was driving me crazy. After adding the `$watch` callback, we can now fill the inputs correctly `` the trip binding has changed from [object Object] to new value Checking to fill user inputs for [object Object] potentialCandidates are 2016-08-04T13:03:51-07:00(1470341031.235) -> 2016-08-04T13:35:12-07:00(1470342912) shared_ride logged at 1632745829.985,2016-08-04T13:03:51-07:00(1470341031.235) -> 2016-08-04T13:35:12-07:00(1470342912) drove_alone logged at 1632745826.26,2016-08-04T13:03:51-07:00(1470341031.235) -> 2016-08-04T13:35:12-07:00(1470342912) shared_ride logged at 1602636485.509,2016-08-04T13:03:51-07:00(1470341031.235) -> 2016-08-04T13:35:12-07:00(1470342912) shared_ride logged at 1602636496.041:undefined ``` + Check in the multi-label-ui for the first time. Better late than never! --- www/js/diary/list.js | 26 +--- www/js/tripconfirm/multi-label-ui.js | 186 +++++++++++++++++++++++++++ www/templates/diary/list.html | 4 +- 3 files changed, 190 insertions(+), 26 deletions(-) create mode 100644 www/js/tripconfirm/multi-label-ui.js diff --git a/www/js/diary/list.js b/www/js/diary/list.js index 0d57dce3f..4dd61f5c8 100644 --- a/www/js/diary/list.js +++ b/www/js/diary/list.js @@ -156,26 +156,6 @@ angular.module('emission.main.diary.list',['ui-leaflet', ionicDatePicker.openDatePicker($scope.datepickerObject); } - /** - * Embed 'inputType' to the trip - */ - $scope.populateInputFromTimeline = function (tripgj, nextTripgj, inputType, inputList) { - var userInput = DiaryHelper.getUserInputForTrip(tripgj, nextTripgj, inputList); - if (angular.isDefined(userInput)) { - // userInput is an object with data + metadata - // the label is the "value" from the options - var userInputEntry = $scope.inputParams[inputType].value2entry[userInput.data.label]; - if (!angular.isDefined(userInputEntry)) { - userInputEntry = ConfirmHelper.getFakeEntry(userInput.data.label); - $scope.inputParams[inputType].options.push(userInputEntry); - $scope.inputParams[inputType].value2entry[userInput.data.label] = userInputEntry; - } - console.log("Mapped label "+userInput.data.label+" to entry "+JSON.stringify(userInputEntry)); - tripgj.userInput[inputType] = userInputEntry; - } - Logger.log("Set "+ inputType + " " + JSON.stringify(userInputEntry) + " for trip id " + JSON.stringify(tripgj.data.id)); - $scope.editingTrip = angular.undefined; - } $scope.populateBasicClasses = function(tripgj) { tripgj.display_start_time = DiaryHelper.getLocalTimeString(tripgj.data.properties.start_local_dt); @@ -231,11 +211,9 @@ angular.module('emission.main.diary.list',['ui-leaflet', DiaryHelper.directiveForTrip); Timeline.setTripWrappers(currDayTripWrappers); + // Add "next" pointers to make it easier to use trip linkages for display $scope.data.currDayTripWrappers.forEach(function(tripgj, tripIndex, array) { - tripgj.userInput = {}; - ConfirmHelper.INPUTS.forEach(function(item, index) { - $scope.populateInputFromTimeline(tripgj, array[tripIndex+1], item, $scope.data.unifiedConfirmsResults[item]); - }); + tripgj.nextTripgj = array[tripIndex+1]; $scope.populateBasicClasses(tripgj); $scope.populateCommonInfo(tripgj); }); diff --git a/www/js/tripconfirm/multi-label-ui.js b/www/js/tripconfirm/multi-label-ui.js new file mode 100644 index 000000000..3ee45e337 --- /dev/null +++ b/www/js/tripconfirm/multi-label-ui.js @@ -0,0 +1,186 @@ +angular.module('emission.tripconfirm.multilabel', + ['emission.tripconfirm.services', + 'emission.main.diary.services']) +.directive('multilabel', function(ConfirmHelper, $ionicPopover, $window, DiaryHelper) { + return { + scope: { + inputs: "=", + tripgj: "=", + unifiedConfirmsResults: "=", + inputParams: "=inputparams" // use nocase inputs to maintain consistency between HTML and scope parameters + }, + controller: function($scope, $element) { + console.log("Invoked directive controller with "+$element); + console.log($scope); + console.log("unifiedresults "+$scope.unifiedConfirmsResults); + console.log("scope trip information is "+$scope.tripgj); + console.log("scope inputs are "+$scope.inputs); + + /** + * Embed 'inputType' to the trip + */ + $scope.populateInputFromTimeline = function (tripgj, nextTripgj, inputType, inputList) { + var userInput = DiaryHelper.getUserInputForTrip(tripgj, nextTripgj, inputList); + if (angular.isDefined(userInput)) { + // userInput is an object with data + metadata + // the label is the "value" from the options + var userInputEntry = $scope.inputParams[inputType].value2entry[userInput.data.label]; + if (!angular.isDefined(userInputEntry)) { + userInputEntry = ConfirmHelper.getFakeEntry(userInput.data.label); + $scope.inputParams[inputType].options.push(userInputEntry); + $scope.inputParams[inputType].value2entry[userInput.data.label] = userInputEntry; + } + console.log("Mapped label "+userInput.data.label+" to entry "+JSON.stringify(userInputEntry)); + tripgj.userInput[inputType] = userInputEntry; + } + Logger.log("Set "+ inputType + " " + JSON.stringify(userInputEntry) + " for trip id " + JSON.stringify(tripgj.data.id)); + $scope.editingTrip = angular.undefined; + } + + $scope.fillUserInputs = function() { + console.log("Checking to fill user inputs for "+$scope.tripgj); + if (angular.isDefined($scope.tripgj)) { + $scope.tripgj.userInput = {}; + ConfirmHelper.INPUTS.forEach(function(item, index) { + $scope.populateInputFromTimeline($scope.tripgj, $scope.tripgj.nextTripgj, + item, $scope.unifiedConfirmsResults[item]); + }); + } else { + console.log("Trip information not yet bound, skipping fill"); + } + } + + $scope.init = function() { + $scope.userInputDetails = []; + $scope.inputs.forEach(function(item, index) { + const currInput = angular.copy(ConfirmHelper.inputDetails[item]); + currInput.name = item; + $scope.userInputDetails.push(currInput); + }); + console.log("Finished initializing directive, userInputDetails = "+JSON.stringify($scope.userInputDetails)); + console.log("Before filling user inputs, trip is = "+JSON.stringify($scope.tripgj)); + } + + $scope.$watch("tripgj", function(newVal, oldVal) { + console.log("the trip binding has changed from "+oldVal+" to new value"); + $scope.fillUserInputs(); + }); + + $scope.popovers = {}; + $scope.inputs.forEach(function(item, index) { + let popoverPath = 'templates/diary/'+item.toLowerCase()+'-popover.html'; + return $ionicPopover.fromTemplateUrl(popoverPath, { + scope: $scope + }).then(function (popover) { + $scope.popovers[item] = popover; + }); + }); + + $scope.openPopover = function ($event, tripgj, inputType) { + var userInput = tripgj.userInput[inputType]; + if (angular.isDefined(userInput)) { + $scope.selected[inputType].value = userInput.value; + } else { + $scope.selected[inputType].value = ''; + } + $scope.draftInput = { + "start_ts": tripgj.data.properties.start_ts, + "end_ts": tripgj.data.properties.end_ts + }; + $scope.editingTrip = tripgj; + Logger.log("in openPopover, setting draftInput = " + JSON.stringify($scope.draftInput)); + $scope.popovers[inputType].show($event); + }; + + var closePopover = function (inputType) { + $scope.selected[inputType] = { + value: '' + }; + $scope.popovers[inputType].hide(); + }; + + /** + * Store selected value for options + * $scope.selected is for display only + * the value is displayed on popover selected option + */ + $scope.selected = {} + $scope.inputs.forEach(function(item, index) { + $scope.selected[item] = {value: ''}; + }); + $scope.selected.other = {text: '', value: ''}; + + /* + * This is a curried function that curries the `$scope` variable + * while returing a function that takes `e` as the input + */ + var checkOtherOptionOnTap = function ($scope, inputType) { + return function (e) { + if (!$scope.selected.other.text) { + e.preventDefault(); + } else { + Logger.log("in choose other, other = " + JSON.stringify($scope.selected)); + $scope.store(inputType, $scope.selected.other, true /* isOther */); + $scope.selected.other = ''; + return $scope.selected.other; + } + } + }; + + $scope.choose = function (inputType) { + var isOther = false + if ($scope.selected[inputType].value != "other") { + $scope.store(inputType, $scope.selected[inputType], isOther); + } else { + isOther = true + ConfirmHelper.checkOtherOption(inputType, checkOtherOptionOnTap, $scope); + } + closePopover(inputType); + }; + + $scope.store = function (inputType, input, isOther) { + if(isOther) { + // Let's make the value for user entered inputs look consistent with our + // other values + input.value = ConfirmHelper.otherTextToValue(input.text); + } + $scope.draftInput.label = input.value; + Logger.log("in storeInput, after setting input.value = " + input.value + ", draftInput = " + JSON.stringify($scope.draftInput)); + var tripToUpdate = $scope.editingTrip; + $window.cordova.plugins.BEMUserCache.putMessage(ConfirmHelper.inputDetails[inputType].key, $scope.draftInput).then(function () { + $scope.$apply(function() { + if (isOther) { + tripToUpdate.userInput[inputType] = ConfirmHelper.getFakeEntry(input.value); + $scope.inputParams[inputType].options.push(tripToUpdate.userInput[inputType]); + $scope.inputParams[inputType].value2entry[input.value] = tripToUpdate.userInput[inputType]; + } else { + tripToUpdate.userInput[inputType] = $scope.inputParams[inputType].value2entry[input.value]; + } + }); + }); + if (isOther == true) + $scope.draftInput = angular.undefined; + } + console.log('registering loaded callback in directive'); + $element.on('$ionicView.loaded', function() { + console.log('ionic view loaded event invoked'); + $scope.inputParams = {} + ConfirmHelper.INPUTS.forEach(function(item) { + ConfirmHelper.getOptionsAndMaps(item).then(function(omObj) { + $scope.inputParams[item] = omObj; + }); + }); + console.log("after loading in directive, inputParams = "+JSON.stringify($scope.inputParams)); + }); + $scope.init(); + }, + templateUrl: 'templates/tripconfirm/multi-label-ui.html', + link: function(scope, element, attrs, ctrl) { + console.log("link function called with "+scope+" and ctrl "+ctrl); + console.log(scope); + console.log("unifiedresults "+scope.unifiedConfirmsResults); + console.log("scope trip information is "+scope.tripgj); + console.log("scope inputs are "+scope.inputs); + } + }; +}); diff --git a/www/templates/diary/list.html b/www/templates/diary/list.html index 8c107bf30..8f6140cc1 100644 --- a/www/templates/diary/list.html +++ b/www/templates/diary/list.html @@ -87,14 +87,14 @@
- +
{{tripgj.display_end_time}}
- + From 52c3326914785ac267172ff3ddec3b2ed31c2d23 Mon Sep 17 00:00:00 2001 From: Shankari Date: Mon, 27 Sep 2021 16:34:00 -0700 Subject: [PATCH 006/175] Some cleanup before the next big stage - Remove the unused link function - Simplify logs by removing several of them and reducing the intensity of others (by not logging the entire object) --- www/js/tripconfirm/multi-label-ui.js | 42 +++++++++++----------------- 1 file changed, 16 insertions(+), 26 deletions(-) diff --git a/www/js/tripconfirm/multi-label-ui.js b/www/js/tripconfirm/multi-label-ui.js index 3ee45e337..d1981b7e4 100644 --- a/www/js/tripconfirm/multi-label-ui.js +++ b/www/js/tripconfirm/multi-label-ui.js @@ -10,11 +10,7 @@ angular.module('emission.tripconfirm.multilabel', inputParams: "=inputparams" // use nocase inputs to maintain consistency between HTML and scope parameters }, controller: function($scope, $element) { - console.log("Invoked directive controller with "+$element); - console.log($scope); - console.log("unifiedresults "+$scope.unifiedConfirmsResults); - console.log("scope trip information is "+$scope.tripgj); - console.log("scope inputs are "+$scope.inputs); + console.log("Invoked multilabel directive controller for labels "+$scope.inputs); /** * Embed 'inputType' to the trip @@ -38,7 +34,8 @@ angular.module('emission.tripconfirm.multilabel', } $scope.fillUserInputs = function() { - console.log("Checking to fill user inputs for "+$scope.tripgj); + console.log("Checking to fill user inputs for " + +$scope.tripgj.display_start_time+" -> "+$scope.tripgj.display_end_time); if (angular.isDefined($scope.tripgj)) { $scope.tripgj.userInput = {}; ConfirmHelper.INPUTS.forEach(function(item, index) { @@ -50,19 +47,8 @@ angular.module('emission.tripconfirm.multilabel', } } - $scope.init = function() { - $scope.userInputDetails = []; - $scope.inputs.forEach(function(item, index) { - const currInput = angular.copy(ConfirmHelper.inputDetails[item]); - currInput.name = item; - $scope.userInputDetails.push(currInput); - }); - console.log("Finished initializing directive, userInputDetails = "+JSON.stringify($scope.userInputDetails)); - console.log("Before filling user inputs, trip is = "+JSON.stringify($scope.tripgj)); - } - $scope.$watch("tripgj", function(newVal, oldVal) { - console.log("the trip binding has changed from "+oldVal+" to new value"); + console.log("the trip binding has changed from "+oldVal+" to new value "+newVal); $scope.fillUserInputs(); }); @@ -172,15 +158,19 @@ angular.module('emission.tripconfirm.multilabel', }); console.log("after loading in directive, inputParams = "+JSON.stringify($scope.inputParams)); }); + + $scope.init = function() { + $scope.userInputDetails = []; + $scope.inputs.forEach(function(item, index) { + const currInput = angular.copy(ConfirmHelper.inputDetails[item]); + currInput.name = item; + $scope.userInputDetails.push(currInput); + }); + console.log("Finished initializing directive, userInputDetails = ", $scope.userInputDetails); + } + $scope.init(); }, - templateUrl: 'templates/tripconfirm/multi-label-ui.html', - link: function(scope, element, attrs, ctrl) { - console.log("link function called with "+scope+" and ctrl "+ctrl); - console.log(scope); - console.log("unifiedresults "+scope.unifiedConfirmsResults); - console.log("scope trip information is "+scope.tripgj); - console.log("scope inputs are "+scope.inputs); - } + templateUrl: 'templates/tripconfirm/multi-label-ui.html' }; }); From a010db8ca387e58eb0e3fe255babcbfcc447ca21 Mon Sep 17 00:00:00 2001 From: Shankari Date: Mon, 27 Sep 2021 16:53:36 -0700 Subject: [PATCH 007/175] Add class "col" to the multilabel so it takes up the entire space in the card like it used to before these changes started --- www/templates/diary/list.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/www/templates/diary/list.html b/www/templates/diary/list.html index 8f6140cc1..3d75cb47d 100644 --- a/www/templates/diary/list.html +++ b/www/templates/diary/list.html @@ -87,7 +87,7 @@
- +
From fc10c6c501e4cf1daaca34e755379ef17dd89258 Mon Sep 17 00:00:00 2001 From: Shankari Date: Mon, 27 Sep 2021 16:57:21 -0700 Subject: [PATCH 008/175] Pull out the controller code into a separate module it is fairly complex, so better to pull it out instead of having it be inline with the directive definition. Now that we know how to include it, we can even move it out to a separate file if it gets really complicated. --- www/js/tripconfirm/multi-label-ui.js | 294 ++++++++++++++------------- 1 file changed, 148 insertions(+), 146 deletions(-) diff --git a/www/js/tripconfirm/multi-label-ui.js b/www/js/tripconfirm/multi-label-ui.js index d1981b7e4..0516ef57c 100644 --- a/www/js/tripconfirm/multi-label-ui.js +++ b/www/js/tripconfirm/multi-label-ui.js @@ -9,168 +9,170 @@ angular.module('emission.tripconfirm.multilabel', unifiedConfirmsResults: "=", inputParams: "=inputparams" // use nocase inputs to maintain consistency between HTML and scope parameters }, - controller: function($scope, $element) { - console.log("Invoked multilabel directive controller for labels "+$scope.inputs); + controller: "MultiLabelCtrl", + templateUrl: 'templates/tripconfirm/multi-label-ui.html' + }; +}) +.controller("MultiLabelCtrl", function($scope, $element, $attrs, + ConfirmHelper, $ionicPopover, $window, DiaryHelper) { + console.log("Invoked multilabel directive controller for labels "+$scope.inputs); - /** - * Embed 'inputType' to the trip - */ - $scope.populateInputFromTimeline = function (tripgj, nextTripgj, inputType, inputList) { - var userInput = DiaryHelper.getUserInputForTrip(tripgj, nextTripgj, inputList); - if (angular.isDefined(userInput)) { - // userInput is an object with data + metadata - // the label is the "value" from the options - var userInputEntry = $scope.inputParams[inputType].value2entry[userInput.data.label]; - if (!angular.isDefined(userInputEntry)) { - userInputEntry = ConfirmHelper.getFakeEntry(userInput.data.label); - $scope.inputParams[inputType].options.push(userInputEntry); - $scope.inputParams[inputType].value2entry[userInput.data.label] = userInputEntry; - } - console.log("Mapped label "+userInput.data.label+" to entry "+JSON.stringify(userInputEntry)); - tripgj.userInput[inputType] = userInputEntry; + /** + * Embed 'inputType' to the trip + */ + $scope.populateInputFromTimeline = function (tripgj, nextTripgj, inputType, inputList) { + var userInput = DiaryHelper.getUserInputForTrip(tripgj, nextTripgj, inputList); + if (angular.isDefined(userInput)) { + // userInput is an object with data + metadata + // the label is the "value" from the options + var userInputEntry = $scope.inputParams[inputType].value2entry[userInput.data.label]; + if (!angular.isDefined(userInputEntry)) { + userInputEntry = ConfirmHelper.getFakeEntry(userInput.data.label); + $scope.inputParams[inputType].options.push(userInputEntry); + $scope.inputParams[inputType].value2entry[userInput.data.label] = userInputEntry; } - Logger.log("Set "+ inputType + " " + JSON.stringify(userInputEntry) + " for trip id " + JSON.stringify(tripgj.data.id)); - $scope.editingTrip = angular.undefined; + console.log("Mapped label "+userInput.data.label+" to entry "+JSON.stringify(userInputEntry)); + tripgj.userInput[inputType] = userInputEntry; } + Logger.log("Set "+ inputType + " " + JSON.stringify(userInputEntry) + " for trip id " + JSON.stringify(tripgj.data.id)); + $scope.editingTrip = angular.undefined; + } - $scope.fillUserInputs = function() { - console.log("Checking to fill user inputs for " - +$scope.tripgj.display_start_time+" -> "+$scope.tripgj.display_end_time); - if (angular.isDefined($scope.tripgj)) { - $scope.tripgj.userInput = {}; - ConfirmHelper.INPUTS.forEach(function(item, index) { - $scope.populateInputFromTimeline($scope.tripgj, $scope.tripgj.nextTripgj, - item, $scope.unifiedConfirmsResults[item]); - }); - } else { - console.log("Trip information not yet bound, skipping fill"); - } - } + $scope.fillUserInputs = function() { + console.log("Checking to fill user inputs for " + +$scope.tripgj.display_start_time+" -> "+$scope.tripgj.display_end_time); + if (angular.isDefined($scope.tripgj)) { + $scope.tripgj.userInput = {}; + ConfirmHelper.INPUTS.forEach(function(item, index) { + $scope.populateInputFromTimeline($scope.tripgj, $scope.tripgj.nextTripgj, + item, $scope.unifiedConfirmsResults[item]); + }); + } else { + console.log("Trip information not yet bound, skipping fill"); + } + } - $scope.$watch("tripgj", function(newVal, oldVal) { - console.log("the trip binding has changed from "+oldVal+" to new value "+newVal); - $scope.fillUserInputs(); - }); - - $scope.popovers = {}; - $scope.inputs.forEach(function(item, index) { - let popoverPath = 'templates/diary/'+item.toLowerCase()+'-popover.html'; - return $ionicPopover.fromTemplateUrl(popoverPath, { - scope: $scope - }).then(function (popover) { - $scope.popovers[item] = popover; - }); + $scope.$watch("tripgj", function(newVal, oldVal) { + console.log("the trip binding has changed from "+oldVal+" to new value "+newVal); + $scope.fillUserInputs(); + }); + + $scope.popovers = {}; + $scope.inputs.forEach(function(item, index) { + let popoverPath = 'templates/diary/'+item.toLowerCase()+'-popover.html'; + return $ionicPopover.fromTemplateUrl(popoverPath, { + scope: $scope + }).then(function (popover) { + $scope.popovers[item] = popover; }); - - $scope.openPopover = function ($event, tripgj, inputType) { - var userInput = tripgj.userInput[inputType]; - if (angular.isDefined(userInput)) { - $scope.selected[inputType].value = userInput.value; - } else { - $scope.selected[inputType].value = ''; - } - $scope.draftInput = { - "start_ts": tripgj.data.properties.start_ts, - "end_ts": tripgj.data.properties.end_ts - }; - $scope.editingTrip = tripgj; - Logger.log("in openPopover, setting draftInput = " + JSON.stringify($scope.draftInput)); - $scope.popovers[inputType].show($event); - }; + }); - var closePopover = function (inputType) { - $scope.selected[inputType] = { - value: '' - }; - $scope.popovers[inputType].hide(); - }; + $scope.openPopover = function ($event, tripgj, inputType) { + var userInput = tripgj.userInput[inputType]; + if (angular.isDefined(userInput)) { + $scope.selected[inputType].value = userInput.value; + } else { + $scope.selected[inputType].value = ''; + } + $scope.draftInput = { + "start_ts": tripgj.data.properties.start_ts, + "end_ts": tripgj.data.properties.end_ts + }; + $scope.editingTrip = tripgj; + Logger.log("in openPopover, setting draftInput = " + JSON.stringify($scope.draftInput)); + $scope.popovers[inputType].show($event); + }; - /** - * Store selected value for options - * $scope.selected is for display only - * the value is displayed on popover selected option - */ - $scope.selected = {} - $scope.inputs.forEach(function(item, index) { - $scope.selected[item] = {value: ''}; - }); - $scope.selected.other = {text: '', value: ''}; + var closePopover = function (inputType) { + $scope.selected[inputType] = { + value: '' + }; + $scope.popovers[inputType].hide(); + }; - /* - * This is a curried function that curries the `$scope` variable - * while returing a function that takes `e` as the input - */ - var checkOtherOptionOnTap = function ($scope, inputType) { - return function (e) { - if (!$scope.selected.other.text) { - e.preventDefault(); - } else { - Logger.log("in choose other, other = " + JSON.stringify($scope.selected)); - $scope.store(inputType, $scope.selected.other, true /* isOther */); - $scope.selected.other = ''; - return $scope.selected.other; - } - } - }; + /** + * Store selected value for options + * $scope.selected is for display only + * the value is displayed on popover selected option + */ + $scope.selected = {} + $scope.inputs.forEach(function(item, index) { + $scope.selected[item] = {value: ''}; + }); + $scope.selected.other = {text: '', value: ''}; - $scope.choose = function (inputType) { - var isOther = false - if ($scope.selected[inputType].value != "other") { - $scope.store(inputType, $scope.selected[inputType], isOther); + /* + * This is a curried function that curries the `$scope` variable + * while returing a function that takes `e` as the input + */ + var checkOtherOptionOnTap = function ($scope, inputType) { + return function (e) { + if (!$scope.selected.other.text) { + e.preventDefault(); } else { - isOther = true - ConfirmHelper.checkOtherOption(inputType, checkOtherOptionOnTap, $scope); + Logger.log("in choose other, other = " + JSON.stringify($scope.selected)); + $scope.store(inputType, $scope.selected.other, true /* isOther */); + $scope.selected.other = ''; + return $scope.selected.other; } - closePopover(inputType); - }; + } + }; + + $scope.choose = function (inputType) { + var isOther = false + if ($scope.selected[inputType].value != "other") { + $scope.store(inputType, $scope.selected[inputType], isOther); + } else { + isOther = true + ConfirmHelper.checkOtherOption(inputType, checkOtherOptionOnTap, $scope); + } + closePopover(inputType); + }; - $scope.store = function (inputType, input, isOther) { - if(isOther) { - // Let's make the value for user entered inputs look consistent with our - // other values - input.value = ConfirmHelper.otherTextToValue(input.text); + $scope.store = function (inputType, input, isOther) { + if(isOther) { + // Let's make the value for user entered inputs look consistent with our + // other values + input.value = ConfirmHelper.otherTextToValue(input.text); + } + $scope.draftInput.label = input.value; + Logger.log("in storeInput, after setting input.value = " + input.value + ", draftInput = " + JSON.stringify($scope.draftInput)); + var tripToUpdate = $scope.editingTrip; + $window.cordova.plugins.BEMUserCache.putMessage(ConfirmHelper.inputDetails[inputType].key, $scope.draftInput).then(function () { + $scope.$apply(function() { + if (isOther) { + tripToUpdate.userInput[inputType] = ConfirmHelper.getFakeEntry(input.value); + $scope.inputParams[inputType].options.push(tripToUpdate.userInput[inputType]); + $scope.inputParams[inputType].value2entry[input.value] = tripToUpdate.userInput[inputType]; + } else { + tripToUpdate.userInput[inputType] = $scope.inputParams[inputType].value2entry[input.value]; } - $scope.draftInput.label = input.value; - Logger.log("in storeInput, after setting input.value = " + input.value + ", draftInput = " + JSON.stringify($scope.draftInput)); - var tripToUpdate = $scope.editingTrip; - $window.cordova.plugins.BEMUserCache.putMessage(ConfirmHelper.inputDetails[inputType].key, $scope.draftInput).then(function () { - $scope.$apply(function() { - if (isOther) { - tripToUpdate.userInput[inputType] = ConfirmHelper.getFakeEntry(input.value); - $scope.inputParams[inputType].options.push(tripToUpdate.userInput[inputType]); - $scope.inputParams[inputType].value2entry[input.value] = tripToUpdate.userInput[inputType]; - } else { - tripToUpdate.userInput[inputType] = $scope.inputParams[inputType].value2entry[input.value]; - } - }); - }); - if (isOther == true) - $scope.draftInput = angular.undefined; - } - console.log('registering loaded callback in directive'); - $element.on('$ionicView.loaded', function() { - console.log('ionic view loaded event invoked'); - $scope.inputParams = {} - ConfirmHelper.INPUTS.forEach(function(item) { - ConfirmHelper.getOptionsAndMaps(item).then(function(omObj) { - $scope.inputParams[item] = omObj; - }); + }); + }); + if (isOther == true) + $scope.draftInput = angular.undefined; + } + console.log('registering loaded callback in directive'); + $element.on('$ionicView.loaded', function() { + console.log('ionic view loaded event invoked'); + $scope.inputParams = {} + ConfirmHelper.INPUTS.forEach(function(item) { + ConfirmHelper.getOptionsAndMaps(item).then(function(omObj) { + $scope.inputParams[item] = omObj; }); - console.log("after loading in directive, inputParams = "+JSON.stringify($scope.inputParams)); }); + console.log("after loading in directive, inputParams = "+JSON.stringify($scope.inputParams)); + }); - $scope.init = function() { - $scope.userInputDetails = []; - $scope.inputs.forEach(function(item, index) { - const currInput = angular.copy(ConfirmHelper.inputDetails[item]); - currInput.name = item; - $scope.userInputDetails.push(currInput); - }); - console.log("Finished initializing directive, userInputDetails = ", $scope.userInputDetails); - } + $scope.init = function() { + $scope.userInputDetails = []; + $scope.inputs.forEach(function(item, index) { + const currInput = angular.copy(ConfirmHelper.inputDetails[item]); + currInput.name = item; + $scope.userInputDetails.push(currInput); + }); + console.log("Finished initializing directive, userInputDetails = ", $scope.userInputDetails); + } - $scope.init(); - }, - templateUrl: 'templates/tripconfirm/multi-label-ui.html' - }; + $scope.init(); }); From 2624cfb74bf31d49c331a8867048bbee85d1aef0 Mon Sep 17 00:00:00 2001 From: Shankari Date: Tue, 28 Sep 2021 16:02:22 -0700 Subject: [PATCH 009/175] Convert the trip-confirm-service into a real singleton MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fortunately, all factories and services are already singletons. https://github.com/e-mission/e-mission-docs/issues/674#issuecomment-929625555 The property is read asynchronously, though, so we have the data that we want to read stored as a promise. The first time we access the field, the async operation completes and the promise completes. In subsequent calls, the promise is fulfilled and will return immediately. This allows us to retain the desired singleton behavior even for an asynchronously read data source. Testing done: Promise executes first and only time ``` Starting promise execution with {} Promise list (2) [Promise, Promise] Read all inputParams, resolving with {} controller DiaryListCtrl called ``` It is then available later but without re-reading or delay ``` While populating inputs, inputParams {MODE: {…}, PURPOSE: {…}} While populating inputs, inputParams {MODE: {…}, PURPOSE: {…}} ``` Introduced a timeout while reading the config ``` diff --git a/www/js/tripconfirm/trip-confirm-services.js b/www/js/tripconfirm/trip-confirm-services.js index 8089362e..291184fa 100644 --- a/www/js/tripconfirm/trip-confirm-services.js +++ b/www/js/tripconfirm/trip-confirm-services.js @@ -1,5 +1,5 @@ angular.module('emission.tripconfirm.services', ['ionic', 'emission.i18n.utils', "emission.plugin.logger"]) -.factory("ConfirmHelper", function($http, $ionicPopup, $translate, i18nUtils, Logger) { +.factory("ConfirmHelper", function($http, $ionicPopup, $translate, i18nUtils, Logger, $timeout) { var ch = {}; ch.INPUTS = ["MODE", "PURPOSE"] ch.inputDetails = { @@ -139,8 +139,10 @@ angular.module('emission.tripconfirm.services', ['ionic', 'emission.i18n.utils', ch.INPUTS.forEach(function(item, index) { inputParams[item] = omObjList[index]; })); - console.log("Read all inputParams, resolving with ", inputParams); - resolve(inputParams); + $timeout(() => { + console.log("Read all inputParams, resolving with ", inputParams); + resolve(inputParams) + }, 60000); }); ``` The promise reading started first ``` Starting promise execution with {} Promise list (2) [Promise, Promise] controller DiaryListCtrl called ``` Then, everything was filled in ``` DEBUG:section 2016-08-04T14:18:35.840464-10:00 -> 2016-08-04T14:34:12.571000-10:00 bound incident addition ``` Several minutes after that, the promise resolved ``` Read all inputParams, resolving with {MODE: {…}, PURPOSE: {…}} Checking to fill user inputs for 10:03 AM -> 10:35 AM While populating inputs, inputParams {MODE: {…}, PURPOSE: {…}} Set MODE {"text":"Shared Ride","value":"shared_ride"} for trip id "5f8646cde070a9164325d554" ``` And the labels were automagically filled in and green. yay for promises! --- www/js/diary/list.js | 13 -------- www/js/tripconfirm/multi-label-ui.js | 37 +++++++++++---------- www/js/tripconfirm/trip-confirm-services.js | 14 ++++++++ www/templates/diary/list.html | 2 +- 4 files changed, 34 insertions(+), 32 deletions(-) diff --git a/www/js/diary/list.js b/www/js/diary/list.js index 4dd61f5c8..b8ccdbf0c 100644 --- a/www/js/diary/list.js +++ b/www/js/diary/list.js @@ -429,19 +429,6 @@ angular.module('emission.main.diary.list',['ui-leaflet', $scope.showModes = DiaryHelper.showModes; - console.log('registering loaded callback'); - $scope.$on('$ionicView.loaded', function() { - console.log('ionic view loaded event invoked'); - $scope.inputParams = {} - ConfirmHelper.INPUTS.forEach(function(item) { - ConfirmHelper.getOptionsAndMaps(item).then(function(omObj) { - $scope.inputParams[item] = omObj; - }); - }); - console.log("after loading, inputParams = "+JSON.stringify($scope.inputParams)); - }); - - $scope.redirect = function(){ $state.go("root.main.current"); }; diff --git a/www/js/tripconfirm/multi-label-ui.js b/www/js/tripconfirm/multi-label-ui.js index 0516ef57c..1af67c883 100644 --- a/www/js/tripconfirm/multi-label-ui.js +++ b/www/js/tripconfirm/multi-label-ui.js @@ -1,13 +1,12 @@ angular.module('emission.tripconfirm.multilabel', ['emission.tripconfirm.services', 'emission.main.diary.services']) -.directive('multilabel', function(ConfirmHelper, $ionicPopover, $window, DiaryHelper) { +.directive('multilabel', function() { return { scope: { inputs: "=", tripgj: "=", unifiedConfirmsResults: "=", - inputParams: "=inputparams" // use nocase inputs to maintain consistency between HTML and scope parameters }, controller: "MultiLabelCtrl", templateUrl: 'templates/tripconfirm/multi-label-ui.html' @@ -21,6 +20,7 @@ angular.module('emission.tripconfirm.multilabel', * Embed 'inputType' to the trip */ $scope.populateInputFromTimeline = function (tripgj, nextTripgj, inputType, inputList) { + console.log("While populating inputs, inputParams", $scope.inputParams); var userInput = DiaryHelper.getUserInputForTrip(tripgj, nextTripgj, inputList); if (angular.isDefined(userInput)) { // userInput is an object with data + metadata @@ -42,10 +42,12 @@ angular.module('emission.tripconfirm.multilabel', console.log("Checking to fill user inputs for " +$scope.tripgj.display_start_time+" -> "+$scope.tripgj.display_end_time); if (angular.isDefined($scope.tripgj)) { - $scope.tripgj.userInput = {}; - ConfirmHelper.INPUTS.forEach(function(item, index) { - $scope.populateInputFromTimeline($scope.tripgj, $scope.tripgj.nextTripgj, - item, $scope.unifiedConfirmsResults[item]); + $scope.$apply(() => { + $scope.tripgj.userInput = {}; + $scope.inputs.forEach(function(item, index) { + $scope.populateInputFromTimeline($scope.tripgj, $scope.tripgj.nextTripgj, + item, $scope.unifiedConfirmsResults[item]); + }); }); } else { console.log("Trip information not yet bound, skipping fill"); @@ -54,7 +56,16 @@ angular.module('emission.tripconfirm.multilabel', $scope.$watch("tripgj", function(newVal, oldVal) { console.log("the trip binding has changed from "+oldVal+" to new value "+newVal); - $scope.fillUserInputs(); + // We also launch this promise from the init. + // If it is complete by the time the watch completes (the common case), the + // promise will return immediately + // but if the promise takes a while, we will still wait here until the data + // is available. + // Think of this as assert(inputParams) + ConfirmHelper.inputParamsPromise.then((inputParams) => { + $scope.inputParams = inputParams; + $scope.fillUserInputs(); + }); }); $scope.popovers = {}; @@ -152,17 +163,6 @@ angular.module('emission.tripconfirm.multilabel', if (isOther == true) $scope.draftInput = angular.undefined; } - console.log('registering loaded callback in directive'); - $element.on('$ionicView.loaded', function() { - console.log('ionic view loaded event invoked'); - $scope.inputParams = {} - ConfirmHelper.INPUTS.forEach(function(item) { - ConfirmHelper.getOptionsAndMaps(item).then(function(omObj) { - $scope.inputParams[item] = omObj; - }); - }); - console.log("after loading in directive, inputParams = "+JSON.stringify($scope.inputParams)); - }); $scope.init = function() { $scope.userInputDetails = []; @@ -171,6 +171,7 @@ angular.module('emission.tripconfirm.multilabel', currInput.name = item; $scope.userInputDetails.push(currInput); }); + ConfirmHelper.inputParamsPromise.then((inputParams) => $scope.inputParams = inputParams); console.log("Finished initializing directive, userInputDetails = ", $scope.userInputDetails); } diff --git a/www/js/tripconfirm/trip-confirm-services.js b/www/js/tripconfirm/trip-confirm-services.js index 5094f0574..8089362e5 100644 --- a/www/js/tripconfirm/trip-confirm-services.js +++ b/www/js/tripconfirm/trip-confirm-services.js @@ -130,5 +130,19 @@ angular.module('emission.tripconfirm.services', ['ionic', 'emission.i18n.utils', value: otherValue}; } + ch.inputParamsPromise = new Promise(function(resolve, reject) { + inputParams = {}; + console.log("Starting promise execution with ", inputParams); + omPromises = ch.INPUTS.map((item) => ch.getOptionsAndMaps(item)); + console.log("Promise list ", omPromises); + Promise.all(omPromises).then((omObjList) => + ch.INPUTS.forEach(function(item, index) { + inputParams[item] = omObjList[index]; + })); + console.log("Read all inputParams, resolving with ", inputParams); + resolve(inputParams); + }); + + return ch; }); diff --git a/www/templates/diary/list.html b/www/templates/diary/list.html index 3d75cb47d..81f909bc0 100644 --- a/www/templates/diary/list.html +++ b/www/templates/diary/list.html @@ -87,7 +87,7 @@
- +
From c9621c30506f54de8b4a33d4d9db40a0310ac072 Mon Sep 17 00:00:00 2001 From: Shankari Date: Tue, 28 Sep 2021 17:56:50 -0700 Subject: [PATCH 010/175] Final cleanup of the main list code Remove all vestiges of the ConfirmHelper code from `list.js` ``` $ grep ConfirmHelper www/js/diary/list.js | wc -l 0 ``` Also remove the list of supported inputs from the directive to avoid duplication with the list in the `ConfirmHelper`. Later, we should clean up `ConfirmHelper` to read that from the config instead of putting it into code. Or if we choose to pass it into the directive, we have to figure out how to pass it in to the factory at creation time. There is no point in configuring it in two places. --- www/js/diary/list.js | 3 +-- www/js/tripconfirm/multi-label-ui.js | 11 +++++------ www/templates/diary/list.html | 2 +- 3 files changed, 7 insertions(+), 9 deletions(-) diff --git a/www/js/diary/list.js b/www/js/diary/list.js index b8ccdbf0c..bee6b7be5 100644 --- a/www/js/diary/list.js +++ b/www/js/diary/list.js @@ -12,7 +12,6 @@ angular.module('emission.main.diary.list',['ui-leaflet', 'ionic-datepicker', 'emission.main.common.services', 'emission.incident.posttrip.manual', - 'emission.tripconfirm.services', 'emission.tripconfirm.multilabel', 'emission.services', 'ng-walkthrough', 'nzTour', 'emission.plugin.kvstore', @@ -25,7 +24,7 @@ angular.module('emission.main.diary.list',['ui-leaflet', $ionicActionSheet, ionicDatePicker, leafletData, Timeline, CommonGraph, DiaryHelper, - Config, PostTripManualMarker, ConfirmHelper, nzTour, KVStore, Logger, UnifiedDataLoader, $ionicPopover, $translate) { + Config, PostTripManualMarker, nzTour, KVStore, Logger, UnifiedDataLoader, $ionicPopover, $translate) { console.log("controller DiaryListCtrl called"); // Add option diff --git a/www/js/tripconfirm/multi-label-ui.js b/www/js/tripconfirm/multi-label-ui.js index 1af67c883..b0cb9f06c 100644 --- a/www/js/tripconfirm/multi-label-ui.js +++ b/www/js/tripconfirm/multi-label-ui.js @@ -4,7 +4,6 @@ angular.module('emission.tripconfirm.multilabel', .directive('multilabel', function() { return { scope: { - inputs: "=", tripgj: "=", unifiedConfirmsResults: "=", }, @@ -14,7 +13,7 @@ angular.module('emission.tripconfirm.multilabel', }) .controller("MultiLabelCtrl", function($scope, $element, $attrs, ConfirmHelper, $ionicPopover, $window, DiaryHelper) { - console.log("Invoked multilabel directive controller for labels "+$scope.inputs); + console.log("Invoked multilabel directive controller for labels "+ConfirmHelper.INPUTS); /** * Embed 'inputType' to the trip @@ -44,7 +43,7 @@ angular.module('emission.tripconfirm.multilabel', if (angular.isDefined($scope.tripgj)) { $scope.$apply(() => { $scope.tripgj.userInput = {}; - $scope.inputs.forEach(function(item, index) { + ConfirmHelper.INPUTS.forEach(function(item, index) { $scope.populateInputFromTimeline($scope.tripgj, $scope.tripgj.nextTripgj, item, $scope.unifiedConfirmsResults[item]); }); @@ -69,7 +68,7 @@ angular.module('emission.tripconfirm.multilabel', }); $scope.popovers = {}; - $scope.inputs.forEach(function(item, index) { + ConfirmHelper.INPUTS.forEach(function(item, index) { let popoverPath = 'templates/diary/'+item.toLowerCase()+'-popover.html'; return $ionicPopover.fromTemplateUrl(popoverPath, { scope: $scope @@ -107,7 +106,7 @@ angular.module('emission.tripconfirm.multilabel', * the value is displayed on popover selected option */ $scope.selected = {} - $scope.inputs.forEach(function(item, index) { + ConfirmHelper.INPUTS.forEach(function(item, index) { $scope.selected[item] = {value: ''}; }); $scope.selected.other = {text: '', value: ''}; @@ -166,7 +165,7 @@ angular.module('emission.tripconfirm.multilabel', $scope.init = function() { $scope.userInputDetails = []; - $scope.inputs.forEach(function(item, index) { + ConfirmHelper.INPUTS.forEach(function(item, index) { const currInput = angular.copy(ConfirmHelper.inputDetails[item]); currInput.name = item; $scope.userInputDetails.push(currInput); diff --git a/www/templates/diary/list.html b/www/templates/diary/list.html index 81f909bc0..a14a99b81 100644 --- a/www/templates/diary/list.html +++ b/www/templates/diary/list.html @@ -87,7 +87,7 @@
- +
From 8a4201d3b746b8d662fb7ce5eea3428a31a8fbda Mon Sep 17 00:00:00 2001 From: Shankari Date: Tue, 28 Sep 2021 23:57:20 -0700 Subject: [PATCH 011/175] First step at unifying the diary and label screens And using the new directive in both places Concretely: - unify the HTML code as per https://github.com/e-mission/e-mission-docs/issues/674#issuecomment-929860996 and https://github.com/e-mission/e-mission-docs/issues/674#issuecomment-929867570 - replace the buttons in the label screen with the new directive - modify the directive slightly to skip `populateInputFromTimeline` if no input label list is passed in. Testing done: - Diary screen shows the trips with green labels - Label screen with the "All Trips" filter shows the trips with green labels --- www/js/tripconfirm/multi-label-ui.js | 43 +++++++++++-------- www/templates/diary/infinite_scroll_list.html | 23 +--------- www/templates/diary/list.html | 2 +- www/templates/tripconfirm/multi-label-ui.html | 22 ++++++---- 4 files changed, 40 insertions(+), 50 deletions(-) diff --git a/www/js/tripconfirm/multi-label-ui.js b/www/js/tripconfirm/multi-label-ui.js index b0cb9f06c..089505c64 100644 --- a/www/js/tripconfirm/multi-label-ui.js +++ b/www/js/tripconfirm/multi-label-ui.js @@ -4,7 +4,7 @@ angular.module('emission.tripconfirm.multilabel', .directive('multilabel', function() { return { scope: { - tripgj: "=", + trip: "=", unifiedConfirmsResults: "=", }, controller: "MultiLabelCtrl", @@ -18,9 +18,9 @@ angular.module('emission.tripconfirm.multilabel', /** * Embed 'inputType' to the trip */ - $scope.populateInputFromTimeline = function (tripgj, nextTripgj, inputType, inputList) { + $scope.populateInputFromTimeline = function (trip, nextTripgj, inputType, inputList) { console.log("While populating inputs, inputParams", $scope.inputParams); - var userInput = DiaryHelper.getUserInputForTrip(tripgj, nextTripgj, inputList); + var userInput = DiaryHelper.getUserInputForTrip(trip, nextTripgj, inputList); if (angular.isDefined(userInput)) { // userInput is an object with data + metadata // the label is the "value" from the options @@ -31,20 +31,20 @@ angular.module('emission.tripconfirm.multilabel', $scope.inputParams[inputType].value2entry[userInput.data.label] = userInputEntry; } console.log("Mapped label "+userInput.data.label+" to entry "+JSON.stringify(userInputEntry)); - tripgj.userInput[inputType] = userInputEntry; + trip.userInput[inputType] = userInputEntry; } - Logger.log("Set "+ inputType + " " + JSON.stringify(userInputEntry) + " for trip id " + JSON.stringify(tripgj.data.id)); + Logger.log("Set "+ inputType + " " + JSON.stringify(userInputEntry) + " for trip id " + JSON.stringify(trip.data.id)); $scope.editingTrip = angular.undefined; } $scope.fillUserInputs = function() { console.log("Checking to fill user inputs for " - +$scope.tripgj.display_start_time+" -> "+$scope.tripgj.display_end_time); - if (angular.isDefined($scope.tripgj)) { + +$scope.trip.display_start_time+" -> "+$scope.trip.display_end_time); + if (angular.isDefined($scope.trip)) { $scope.$apply(() => { - $scope.tripgj.userInput = {}; + $scope.trip.userInput = {}; ConfirmHelper.INPUTS.forEach(function(item, index) { - $scope.populateInputFromTimeline($scope.tripgj, $scope.tripgj.nextTripgj, + $scope.populateInputFromTimeline($scope.trip, $scope.trip.nextTripgj, item, $scope.unifiedConfirmsResults[item]); }); }); @@ -53,7 +53,7 @@ angular.module('emission.tripconfirm.multilabel', } } - $scope.$watch("tripgj", function(newVal, oldVal) { + $scope.$watch("trip", function(newVal, oldVal) { console.log("the trip binding has changed from "+oldVal+" to new value "+newVal); // We also launch this promise from the init. // If it is complete by the time the watch completes (the common case), the @@ -61,10 +61,15 @@ angular.module('emission.tripconfirm.multilabel', // but if the promise takes a while, we will still wait here until the data // is available. // Think of this as assert(inputParams) - ConfirmHelper.inputParamsPromise.then((inputParams) => { - $scope.inputParams = inputParams; - $scope.fillUserInputs(); - }); + if ($scope.unifiedConfirmsResults != undefined) { + ConfirmHelper.inputParamsPromise.then((inputParams) => { + $scope.inputParams = inputParams; + $scope.fillUserInputs(); + }); + console.log("After filling user inputs", $scope.trip); + } else { + console.log("No input list defined, skipping manual user input fill", $scope.unifiedConfirmsResults); + } }); $scope.popovers = {}; @@ -77,18 +82,18 @@ angular.module('emission.tripconfirm.multilabel', }); }); - $scope.openPopover = function ($event, tripgj, inputType) { - var userInput = tripgj.userInput[inputType]; + $scope.openPopover = function ($event, trip, inputType) { + var userInput = trip.userInput[inputType]; if (angular.isDefined(userInput)) { $scope.selected[inputType].value = userInput.value; } else { $scope.selected[inputType].value = ''; } $scope.draftInput = { - "start_ts": tripgj.data.properties.start_ts, - "end_ts": tripgj.data.properties.end_ts + "start_ts": trip.data.properties.start_ts, + "end_ts": trip.data.properties.end_ts }; - $scope.editingTrip = tripgj; + $scope.editingTrip = trip; Logger.log("in openPopover, setting draftInput = " + JSON.stringify($scope.draftInput)); $scope.popovers[inputType].show($event); }; diff --git a/www/templates/diary/infinite_scroll_list.html b/www/templates/diary/infinite_scroll_list.html index 436e13e5d..879ca1167 100644 --- a/www/templates/diary/infinite_scroll_list.html +++ b/www/templates/diary/infinite_scroll_list.html @@ -77,28 +77,7 @@

{{'diary.scroll-to-load-more' | transla
-
- {{input.labeltext}} -
-
-
-
-
- -
-
- -
-
- -
-
+
diff --git a/www/templates/diary/list.html b/www/templates/diary/list.html index a14a99b81..f8ba4341c 100644 --- a/www/templates/diary/list.html +++ b/www/templates/diary/list.html @@ -87,7 +87,7 @@
- +
diff --git a/www/templates/tripconfirm/multi-label-ui.html b/www/templates/tripconfirm/multi-label-ui.html index b579a54a1..413b74e7e 100644 --- a/www/templates/tripconfirm/multi-label-ui.html +++ b/www/templates/tripconfirm/multi-label-ui.html @@ -1,20 +1,26 @@ -
+
{{input.labeltext}}
-
+
-
-
- -
- +
+ +
+
From eb1fd9790c27211e7b47030395ad4f0654c41885 Mon Sep 17 00:00:00 2001 From: Shankari Date: Fri, 1 Oct 2021 17:28:51 -0700 Subject: [PATCH 012/175] Initial version of the "verify check" button linked to the multilabel screen MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Detailed investigation into the linkage is at: https://github.com/e-mission/e-mission-docs/issues/674#issuecomment-930224805 to https://github.com/e-mission/e-mission-docs/issues/674#issuecomment-932634418 Also changed the formatting of the diary screen a bit to clear some space for the verify check button. Note that we needed to reduce the scope of the `toDetail` call in that case, since it will result in both confirming and going to the detail screen. Testing done: Clicked on the "VC" button in both the diary and the infinite list screens. Got the click and found the corresponding multilabel in both cases. ``` element is S.fn.init [verifycheck.col-10.diarycheckmark-container] parent row is S.fn.init [ion-item#diary-item.list-item.item, prevObject: S.fn.init(1)] row Element is S.fn.init [ion-item#diary-item.list-item.item, prevObject: S.fn.init(1)] child multilabel is S.fn.init [multilabel.col, prevObject: S.fn.init(1)] multilabel scope is Scope {$id: 2455, $$childTail: Scope, $$childHead: Scope, $$prevSibling: Scope, $$nextSibling: null, …} ``` --- www/index.html | 1 + www/js/diary/infinite_scroll_list.js | 1 + www/js/diary/list.js | 1 + www/js/tripconfirm/one-click-button.js | 22 +++++++++++++++++++ www/templates/diary/infinite_scroll_list.html | 3 +++ www/templates/diary/list.html | 15 ++++++++----- 6 files changed, 38 insertions(+), 5 deletions(-) create mode 100644 www/js/tripconfirm/one-click-button.js diff --git a/www/index.html b/www/index.html index e242f95ec..2795caf8d 100644 --- a/www/index.html +++ b/www/index.html @@ -83,6 +83,7 @@ + diff --git a/www/js/diary/infinite_scroll_list.js b/www/js/diary/infinite_scroll_list.js index cfbf302f9..525a2c76a 100644 --- a/www/js/diary/infinite_scroll_list.js +++ b/www/js/diary/infinite_scroll_list.js @@ -13,6 +13,7 @@ angular.module('emission.main.diary.infscrolllist',['ui-leaflet', 'emission.main.common.services', 'emission.incident.posttrip.manual', 'emission.tripconfirm.services', + 'emission.tripconfirm.verifycheck', 'emission.services', 'ng-walkthrough', 'nzTour', 'emission.plugin.kvstore', 'emission.main.diary.infscrollfilters', diff --git a/www/js/diary/list.js b/www/js/diary/list.js index bee6b7be5..26609edaf 100644 --- a/www/js/diary/list.js +++ b/www/js/diary/list.js @@ -13,6 +13,7 @@ angular.module('emission.main.diary.list',['ui-leaflet', 'emission.main.common.services', 'emission.incident.posttrip.manual', 'emission.tripconfirm.multilabel', + 'emission.tripconfirm.verifycheck', 'emission.services', 'ng-walkthrough', 'nzTour', 'emission.plugin.kvstore', 'emission.plugin.logger' diff --git a/www/js/tripconfirm/one-click-button.js b/www/js/tripconfirm/one-click-button.js new file mode 100644 index 000000000..34574959a --- /dev/null +++ b/www/js/tripconfirm/one-click-button.js @@ -0,0 +1,22 @@ +angular.module('emission.tripconfirm.verifycheck', + ['emission.tripconfirm.services', + 'emission.main.diary.services']) +.directive('verifycheck', function($timeout) { + return { + scope: { + }, + link: function(scope, element, attrs, controllers) { + element.on('click', function(event) { + console.log("element is ", element); + console.log("parent row is", element.parents("ion-item")); + let rowElement = element.parents("ion-item") + console.log("row Element is", rowElement); + let multilabel = rowElement.find("multilabel"); + console.log("child multilabel is", multilabel); + let multilabelScope = angular.element(multilabel).isolateScope(); + console.log("multilabel scope is", multilabelScope); + }); + }, + template: 'VC' + }; +}) diff --git a/www/templates/diary/infinite_scroll_list.html b/www/templates/diary/infinite_scroll_list.html index 879ca1167..ced6b815c 100644 --- a/www/templates/diary/infinite_scroll_list.html +++ b/www/templates/diary/infinite_scroll_list.html @@ -72,9 +72,12 @@

{{'diary.scroll-to-load-more' | transla {{trip.end_display_name}}

+ +
diff --git a/www/templates/diary/list.html b/www/templates/diary/list.html index f8ba4341c..cc9e430c4 100644 --- a/www/templates/diary/list.html +++ b/www/templates/diary/list.html @@ -47,10 +47,10 @@
-
+
-
+

@@ -68,7 +68,12 @@
- +
+ + +
+
@@ -81,8 +86,8 @@ {{tripgj.end_place.properties.display_name.split(',')[0]}}
-
- +
+
From 0f22450c7a6fc6ec63562ad351aa4db3512e26c0 Mon Sep 17 00:00:00 2001 From: Shankari Date: Sat, 2 Oct 2021 11:27:30 -0700 Subject: [PATCH 013/175] Link the two directives completely and generalizably - Pass in the tagName of the label button to verifycheck - Look up element with the tagName dynamically (similar to eb1fd9790c27211e7b47030395ad4f0654c41885) - Actually invoke a method on its scope + move the verifyTrip code from `infinite_scroll_list.js` to the multi-label code so that it can be invoked from the scope. + move the verifiability initialization from infinite_scroll_list to the verify directive since it is basically initialization code + Move the verify check HTML code from the `infinite_scroll_list` HTML code to a separate template HTML so that it actually shows a check mark instead of "VC" --- www/js/diary/infinite_scroll_list.js | 2 +- www/js/tripconfirm/multi-label-ui.js | 42 ++++++++++++++++++- www/js/tripconfirm/one-click-button.js | 36 ++++++++++------ www/templates/diary/infinite_scroll_list.html | 8 +--- www/templates/diary/list.html | 4 +- .../tripconfirm/one-click-button.html | 3 ++ 6 files changed, 72 insertions(+), 23 deletions(-) create mode 100644 www/templates/tripconfirm/one-click-button.html diff --git a/www/js/diary/infinite_scroll_list.js b/www/js/diary/infinite_scroll_list.js index 525a2c76a..9a11048a1 100644 --- a/www/js/diary/infinite_scroll_list.js +++ b/www/js/diary/infinite_scroll_list.js @@ -469,6 +469,7 @@ angular.module('emission.main.diary.infscrolllist',['ui-leaflet', trip.verifiability = someYellow ? "can-verify" : (allGreen ? "already-verified" : "cannot-verify"); } + $scope.getFormattedDistanceInMiles = function(input) { return (0.621371 * $scope.getFormattedDistance(input)).toFixed(1); } @@ -482,7 +483,6 @@ angular.module('emission.main.diary.infscrolllist',['ui-leaflet', tripgj.end_ts); tripgj.background = "bg-light"; tripgj.listCardClass = $scope.listCardClass(tripgj); - tripgj.verifiability = "cannot-verify"; // Pre-populate start and end names with   so they take up the same amount of vertical space in the UI before they are populated with real data tripgj.start_display_name = "\xa0"; tripgj.end_display_name = "\xa0"; diff --git a/www/js/tripconfirm/multi-label-ui.js b/www/js/tripconfirm/multi-label-ui.js index 089505c64..8f37d9cf3 100644 --- a/www/js/tripconfirm/multi-label-ui.js +++ b/www/js/tripconfirm/multi-label-ui.js @@ -1,5 +1,6 @@ angular.module('emission.tripconfirm.multilabel', ['emission.tripconfirm.services', + 'emission.stats.clientstats', 'emission.main.diary.services']) .directive('multilabel', function() { return { @@ -12,9 +13,48 @@ angular.module('emission.tripconfirm.multilabel', }; }) .controller("MultiLabelCtrl", function($scope, $element, $attrs, - ConfirmHelper, $ionicPopover, $window, DiaryHelper) { + ConfirmHelper, $ionicPopover, $window, DiaryHelper, ClientStats) { console.log("Invoked multilabel directive controller for labels "+ConfirmHelper.INPUTS); + /** + * BEGIN: Required external interface for all label directives + * These methods will be invoked by the verifycheck directive + * For more details on cooperating directives in this situation, please see: + * e-mission/e-mission-docs#674 (comment) + * to + * e-mission/e-mission-docs#674 (comment) + * + * Input: none + * Side effect: verifies the trip (partially if needed) and updates the trip + * verifiability status. + */ + $scope.verifyTrip = function() { + console.log("About to verify trip "+$scope.trip.start_ts + +" -> "+$scope.trip.end_ts+" with current visibility" + + $scope.trip.verifiability); + if ($scope.trip.verifiability != "can-verify") { + ClientStats.addReading(ClientStats.getStatKeys().VERIFY_TRIP, {"verifiable": false}); + return; + } + ClientStats.addReading(ClientStats.getStatKeys().VERIFY_TRIP, {"verifiable": true, "userInput": angular.toJson(trip.userInput), "finalInference": angular.toJson(trip.finalInference)}); + + $scope.draftInput = { + "start_ts": trip.start_ts, + "end_ts": trip.end_ts + }; + $scope.editingTrip = trip; + + for (const inputType of ConfirmHelper.INPUTS) { + const inferred = trip.finalInference[inputType]; + // TODO: figure out what to do with "other". For now, do not verify. + if (inferred && !trip.userInput[inputType] && inferred != "other") $scope.store(inputType, inferred, false); + } + } + + /* + * END: Required external interface for all label directives + */ + /** * Embed 'inputType' to the trip */ diff --git a/www/js/tripconfirm/one-click-button.js b/www/js/tripconfirm/one-click-button.js index 34574959a..6cdedc9ff 100644 --- a/www/js/tripconfirm/one-click-button.js +++ b/www/js/tripconfirm/one-click-button.js @@ -4,19 +4,29 @@ angular.module('emission.tripconfirm.verifycheck', .directive('verifycheck', function($timeout) { return { scope: { + linkedtag: "@", + trip: "=", + invokedfrom: "=" }, - link: function(scope, element, attrs, controllers) { - element.on('click', function(event) { - console.log("element is ", element); - console.log("parent row is", element.parents("ion-item")); - let rowElement = element.parents("ion-item") - console.log("row Element is", rowElement); - let multilabel = rowElement.find("multilabel"); - console.log("child multilabel is", multilabel); - let multilabelScope = angular.element(multilabel).isolateScope(); - console.log("multilabel scope is", multilabelScope); - }); - }, - template: 'VC' + controller: "OneClickButtonCtrl", + templateUrl: 'templates/tripconfirm/one-click-button.html' }; }) +.controller("OneClickButtonCtrl", function($scope, $element, $attrs) { + var findLinkedLabelScope = function() { + console.log("$element is ", $element); + console.log("parent row is", $element.parents("ion-item")); + let rowElement = $element.parents("ion-item") + console.log("row Element is", rowElement); + let linkedlabel = rowElement.find($scope.linkedtag); + console.log("child linkedlabel is", linkedlabel); + let linkedlabelScope = angular.element(linkedlabel).isolateScope(); + console.log("linkedlabel scope is", linkedlabelScope); + return linkedlabelScope; + }; + + $scope.verifyTrip = function() { + let linkedLabelScope = findLinkedLabelScope(); + linkedLabelScope.verifyTrip(); + } +}); diff --git a/www/templates/diary/infinite_scroll_list.html b/www/templates/diary/infinite_scroll_list.html index ced6b815c..a9cf24bf7 100644 --- a/www/templates/diary/infinite_scroll_list.html +++ b/www/templates/diary/infinite_scroll_list.html @@ -72,12 +72,8 @@

{{'diary.scroll-to-load-more' | transla {{trip.end_display_name}}

- - +
diff --git a/www/templates/diary/list.html b/www/templates/diary/list.html index cc9e430c4..ac16d96cb 100644 --- a/www/templates/diary/list.html +++ b/www/templates/diary/list.html @@ -86,8 +86,8 @@ {{tripgj.end_place.properties.display_name.split(',')[0]}}
-
- +
+
diff --git a/www/templates/tripconfirm/one-click-button.html b/www/templates/tripconfirm/one-click-button.html new file mode 100644 index 000000000..b6a128888 --- /dev/null +++ b/www/templates/tripconfirm/one-click-button.html @@ -0,0 +1,3 @@ +
+ +
From 37439dc9638748b4fa0d4d62065dc318b9801f68 Mon Sep 17 00:00:00 2001 From: Shankari Date: Sun, 3 Oct 2021 17:48:07 -0700 Subject: [PATCH 014/175] Labeling code: infinite scroll list -> directive Move all the labeling code from the infinite scroll list to the directive Concretely: - remove the input detail initialization - move out the code which initializes the inputs and replace it with the nextTrip link - move the manual input population code as well. this is now a separate implementation from the diary initialization code; we will need to unify it later - move related functions to the directive: - `populateInput`, - `populateManualInputs`, - `updateVisibilityAfterDelay`, - `updateTripProperties`, - `inferFinalLabels`, - `updateVerifiability` - delete functions that were already copied from the diary, with minor modifications as necessary: - create `$scope.popovers`, - `$scope.openPopover` - `$scope.choose` - `closePopover` - `$scope.verifyTrip` also copied `trip.properties.*_ts` into `trip.*_ts` so we can have the same implementation for both data structures (https://github.com/e-mission/e-mission-docs/issues/674#issuecomment-932833288) In addition, in the directive, we do the following: - add functions to find the view element, its state and scope. - We will use this state to indicate which view we are working with, given that we plan to support labeling assist in the diary view as well (https://github.com/e-mission/e-mission-docs/issues/674#issuecomment-932833288) - We will use the scope to callback to the view and filter the trips accordingly (https://github.com/e-mission/e-mission-docs/issues/674#issuecomment-932833288) This almost works. The one pending issue is that of filtering to set `$scope.displayTrips`. In `$scope.setupInfScroll`, we read entries from the server (`$scope.readDataFromServer`), which sets `$scope.data.allTrips`. It then calls `$scope.recomputeDisplayTrip` which uses the userInputs to decide which trips should be in `$scope.displayTrips`. The problem is that we set the userInputs in the directive. However, the directives are not executed until they are displayed. So until we compute which trips go into `displayTrips`, we will not execute the directives, which means that we will not have the fields we need to compute the directives. We need to resolve this circular dependency. --- www/js/diary/infinite_scroll_list.js | 312 +----------------- www/js/tripconfirm/multi-label-ui.js | 295 +++++++++++++++-- www/templates/diary/infinite_scroll_list.html | 5 +- www/templates/diary/list.html | 3 +- 4 files changed, 282 insertions(+), 333 deletions(-) diff --git a/www/js/diary/infinite_scroll_list.js b/www/js/diary/infinite_scroll_list.js index 9a11048a1..4480d8129 100644 --- a/www/js/diary/infinite_scroll_list.js +++ b/www/js/diary/infinite_scroll_list.js @@ -28,7 +28,7 @@ angular.module('emission.main.diary.infscrolllist',['ui-leaflet', ionicDatePicker, leafletData, Timeline, CommonGraph, DiaryHelper, InfScrollFilters, - Config, PostTripManualMarker, ConfirmHelper, nzTour, KVStore, Logger, UnifiedDataLoader, $ionicPopover, $ionicModal, $translate, $q) { + Config, PostTripManualMarker, nzTour, KVStore, Logger, UnifiedDataLoader, $ionicPopover, $ionicModal, $translate, $q) { // TODO: load only a subset of entries instead of everything @@ -37,13 +37,6 @@ angular.module('emission.main.diary.infscrolllist',['ui-leaflet', const placeLimiter = new Bottleneck({ maxConcurrent: 2, minTime: 500 }); - $scope.userInputDetails = []; - ConfirmHelper.INPUTS.forEach(function(item, index) { - const currInput = angular.copy(ConfirmHelper.inputDetails[item]); - currInput.name = item; - $scope.userInputDetails.push(currInput); - }); - $scope.data = {}; $scope.getActiveFilters = function() { @@ -106,15 +99,7 @@ angular.module('emission.main.diary.infscrolllist',['ui-leaflet', Logger.log("Received batch of size "+ctList.length); ctList.forEach($scope.populateBasicClasses); ctList.forEach((trip, tIndex) => { - // console.log("Expectation: "+JSON.stringify(trip.expectation)); - // console.log("Inferred labels from server: "+JSON.stringify(trip.inferred_labels)); - trip.userInput = {}; - ConfirmHelper.INPUTS.forEach(function(item, index) { - $scope.populateManualInputs(trip, ctList[tIndex+1], item, $scope.data.manualResultMap[item]); - }); - trip.finalInference = {}; - $scope.inferFinalLabels(trip); - $scope.updateVerifiability(trip); + trip.nextTrip = ctList[tIndex+1]; }); // Fill places on a reversed copy of the list so we fill from the bottom up ctList.slice().reverse().forEach(function(trip, index) { @@ -159,7 +144,10 @@ angular.module('emission.main.diary.infscrolllist',['ui-leaflet', $scope.data.displayTrips = []; Timeline.getUnprocessedLabels().then(([pipelineRange, manualResultMap]) => { if (pipelineRange.end_ts) { - $scope.data.manualResultMap = manualResultMap; + $scope.$apply(() => { + $scope.data.manualResultMap = manualResultMap; + }); + console.log("After reading in the label controller, manualResultMap "+JSON.stringify($scope.manualResultMap), $scope.data.manualResultMap); $scope.infScrollControl.pipelineRange = pipelineRange; $scope.infScrollControl.currentEnd = pipelineRange.end_ts; $scope.infScrollControl.callback = function() { @@ -317,159 +305,6 @@ angular.module('emission.main.diary.infscrolllist',['ui-leaflet', return ($scope.differentCommon(tripgj))? "stop-time-tag-lower" : "stop-time-tag"; } - /** - * MODE (becomes manual/mode_confirm) becomes mode_confirm - */ - $scope.inputType2retKey = function(inputType) { - return ConfirmHelper.inputDetails[inputType].key.split("/")[1]; - } - - /** - * Insert the given userInputLabel into the given inputType's slot in inputField - */ - $scope.populateInput = function(tripField, inputType, userInputLabel) { - if (angular.isDefined(userInputLabel)) { - var userInputEntry = $scope.inputParams[inputType].value2entry[userInputLabel]; - if (!angular.isDefined(userInputEntry)) { - userInputEntry = ConfirmHelper.getFakeEntry(userInputLabel); - $scope.inputParams[inputType].options.push(userInputEntry); - $scope.inputParams[inputType].value2entry[userInputLabel] = userInputEntry; - } - // console.log("Mapped label "+userInputLabel+" to entry "+JSON.stringify(userInputEntry)); - tripField[inputType] = userInputEntry; - } - } - - /** - * Embed 'inputType' to the trip - */ - $scope.populateManualInputs = function (tripgj, nextTripgj, inputType, inputList) { - // Check unprocessed labels first since they are more recent - // Massage the input to meet getUserInputForTrip expectations - const unprocessedLabelEntry = DiaryHelper.getUserInputForTrip( - {data: {properties: tripgj, features: [{}, {}, {}]}}, - {data: {properties: nextTripgj, features: [{}, {}, {}]}}, - inputList); - var userInputLabel = unprocessedLabelEntry? unprocessedLabelEntry.data.label : undefined; - if (!angular.isDefined(userInputLabel)) { - userInputLabel = tripgj.user_input[$scope.inputType2retKey(inputType)]; - } - $scope.populateInput(tripgj.userInput, inputType, userInputLabel); - // Logger.log("Set "+ inputType + " " + JSON.stringify(userInputEntry) + " for trip starting at " + JSON.stringify(tripgj.start_fmt_time)); - $scope.editingTrip = angular.undefined; - } - - /* - * Embody the logic for delayed update: - * the recompute logic already keeps trips that are waitingForModification - * even if they would be filtered otherwise. - * so here: - * - set the trip as waiting for potential modifications - * - create a one minute timeout that will remove the wait and recompute - * - clear the existing timeout (if any) - */ - $scope.updateVisibilityAfterDelay = function(trip) { - // We have just edited this trip, and are now waiting to see if the user - // is going to modify it further - trip.waitingForMod = true; - let currTimeoutPromise = trip.timeoutPromise; - let THIRTY_SECS = 30 * 1000; - Logger.log("trip starting at "+trip.start_fmt_time+": creating new timeout"); - trip.timeoutPromise = $timeout(function() { - Logger.log("trip starting at "+trip.start_fmt_time+": executing recompute"); - trip.waitingForMod = false; - trip.timeoutPromise = undefined; - $scope.recomputeDisplayTrips(); - }, THIRTY_SECS); - Logger.log("trip starting at "+trip.start_fmt_time+": cancelling existing timeout "+currTimeoutPromise); - $timeout.cancel(currTimeoutPromise); - } - - $scope.updateTripProperties = function(trip) { - $scope.inferFinalLabels(trip); - $scope.updateVerifiability(trip); - $scope.updateVisibilityAfterDelay(trip); - } - - /** - * Given the list of possible label tuples we've been sent and what the user has already input for the trip, choose the best labels to actually present to the user. - * The algorithm below operationalizes these principles: - * - Never consider label tuples that contradict a green label - * - Obey "conservation of uncertainty": the sum of probabilities after filtering by green labels must equal the sum of probabilities before - * - After filtering, predict the most likely choices at the level of individual labels, not label tuples - * - Never show user yellow labels that have a lower probability of being correct than confidenceThreshold - */ - $scope.inferFinalLabels = function(trip) { - // Deep copy the possibility tuples - let labelsList = []; - if (angular.isDefined(trip.inferred_labels)) { - labelsList = JSON.parse(JSON.stringify(trip.inferred_labels)); - } - - // Capture the level of certainty so we can reconstruct it later - const totalCertainty = labelsList.map(item => item.p).reduce(((item, rest) => item + rest), 0); - - // Filter out the tuples that are inconsistent with existing green labels - for (const inputType of ConfirmHelper.INPUTS) { - const userInput = trip.userInput[inputType]; - if (userInput) { - const retKey = $scope.inputType2retKey(inputType); - labelsList = labelsList.filter(item => item.labels[retKey] == userInput.value); - } - } - - // Red labels if we have no possibilities left - if (labelsList.length == 0) { - for (const inputType of ConfirmHelper.INPUTS) $scope.populateInput(trip.finalInference, inputType, undefined); - } - else { - // Normalize probabilities to previous level of certainty - const certaintyScalar = totalCertainty/labelsList.map(item => item.p).reduce((item, rest) => item + rest); - labelsList.forEach(item => item.p*=certaintyScalar); - - for (const inputType of ConfirmHelper.INPUTS) { - // For each label type, find the most probable value by binning by label value and summing - const retKey = $scope.inputType2retKey(inputType); - let valueProbs = new Map(); - for (const tuple of labelsList) { - const labelValue = tuple.labels[retKey]; - if (!valueProbs.has(labelValue)) valueProbs.set(labelValue, 0); - valueProbs.set(labelValue, valueProbs.get(labelValue) + tuple.p); - } - let max = {p: 0, labelValue: undefined}; - for (const [thisLabelValue, thisP] of valueProbs) { - // In the case of a tie, keep the label with earlier first appearance in the labelsList (we used a Map to preserve this order) - if (thisP > max.p) max = {p: thisP, labelValue: thisLabelValue}; - } - - // Display a label as red if its most probable inferred value has a probability less than or equal to the trip's confidence_threshold - // Fails safe if confidence_threshold doesn't exist - if (max.p <= trip.confidence_threshold) max.labelValue = undefined; - - $scope.populateInput(trip.finalInference, inputType, max.labelValue); - } - } - } - - /** - * For a given trip, compute how the "verify" button should behave. - * If the trip has at least one yellow label, the button should be clickable. - * If the trip has all green labels, the button should be disabled because everything has already been verified. - * If the trip has all red labels or a mix of red and green, the button should be disabled because we need more detailed user input. - */ - $scope.updateVerifiability = function(trip) { - var allGreen = true; - var someYellow = false; - for (const inputType of ConfirmHelper.INPUTS) { - const green = trip.userInput[inputType]; - const yellow = trip.finalInference[inputType] && !green; - if (yellow) someYellow = true; - if (!green) allGreen = false; - } - trip.verifiability = someYellow ? "can-verify" : (allGreen ? "already-verified" : "cannot-verify"); - } - - $scope.getFormattedDistanceInMiles = function(input) { return (0.621371 * $scope.getFormattedDistance(input)).toFixed(1); } @@ -753,141 +588,6 @@ angular.module('emission.main.diary.infscrolllist',['ui-leaflet', $scope.showModes = DiaryHelper.showModes; - $scope.popovers = {}; - ConfirmHelper.INPUTS.forEach(function(item, index) { - let popoverPath = 'templates/diary/'+item.toLowerCase()+'-popover.html'; - return $ionicPopover.fromTemplateUrl(popoverPath, { - scope: $scope - }).then(function (popover) { - $scope.popovers[item] = popover; - }); - }); - - $scope.openPopover = function ($event, tripgj, inputType) { - var userInput = tripgj.userInput[inputType]; - if (angular.isDefined(userInput)) { - $scope.selected[inputType].value = userInput.value; - } else { - $scope.selected[inputType].value = ''; - } - $scope.draftInput = { - "start_ts": tripgj.start_ts, - "end_ts": tripgj.end_ts - }; - $scope.editingTrip = tripgj; - Logger.log("in openPopover, setting draftInput = " + JSON.stringify($scope.draftInput)); - $scope.popovers[inputType].show($event); - }; - - var closePopover = function (inputType) { - $scope.selected[inputType] = { - value: '' - }; - $scope.popovers[inputType].hide(); - }; - - /** - * verifyTrip turns all of a given trip's yellow labels green - */ - $scope.verifyTrip = function($event, trip) { - if (trip.verifiability != "can-verify") { - ClientStats.addReading(ClientStats.getStatKeys().VERIFY_TRIP, {"verifiable": false}); - return; - } - ClientStats.addReading(ClientStats.getStatKeys().VERIFY_TRIP, {"verifiable": true, "userInput": angular.toJson(trip.userInput), "finalInference": angular.toJson(trip.finalInference)}); - - $scope.draftInput = { - "start_ts": trip.start_ts, - "end_ts": trip.end_ts - }; - $scope.editingTrip = trip; - - for (const inputType of ConfirmHelper.INPUTS) { - const inferred = trip.finalInference[inputType]; - // TODO: figure out what to do with "other". For now, do not verify. - if (inferred && !trip.userInput[inputType] && inferred != "other") $scope.store(inputType, inferred, false); - } - } - - /** - * Store selected value for options - * $scope.selected is for display only - * the value is displayed on popover selected option - */ - $scope.selected = {} - ConfirmHelper.INPUTS.forEach(function(item, index) { - $scope.selected[item] = {value: ''}; - }); - $scope.selected.other = {text: '', value: ''}; - - /* - * This is a curried function that curries the `$scope` variable - * while returing a function that takes `e` as the input - */ - var checkOtherOptionOnTap = function ($scope, inputType) { - return function (e) { - if (!$scope.selected.other.text) { - e.preventDefault(); - } else { - Logger.log("in choose other, other = " + JSON.stringify($scope.selected)); - $scope.store(inputType, $scope.selected.other, true /* isOther */); - $scope.selected.other = ''; - return $scope.selected.other; - } - } - }; - - $scope.choose = function (inputType) { - ClientStats.addReading(ClientStats.getStatKeys().SELECT_LABEL, { - "userInput": angular.toJson($scope.editingTrip.userInput), - "finalInference": angular.toJson($scope.editingTrip.finalInference), - "inputKey": inputType, - "inputVal": $scope.selected[inputType].value - }); - var isOther = false - if ($scope.selected[inputType].value != "other") { - $scope.store(inputType, $scope.selected[inputType], isOther); - } else { - isOther = true - ConfirmHelper.checkOtherOption(inputType, checkOtherOptionOnTap, $scope); - } - closePopover(inputType); - }; - - $scope.$on('$ionicView.loaded', function() { - $scope.inputParams = {} - ConfirmHelper.INPUTS.forEach(function(item) { - ConfirmHelper.getOptionsAndMaps(item).then(function(omObj) { - $scope.inputParams[item] = omObj; - }); - }); - }); - - $scope.store = function (inputType, input, isOther) { - if(isOther) { - // Let's make the value for user entered inputs look consistent with our - // other values - input.value = ConfirmHelper.otherTextToValue(input.text); - } - $scope.draftInput.label = input.value; - Logger.log("in storeInput, after setting input.value = " + input.value + ", draftInput = " + JSON.stringify($scope.draftInput)); - var tripToUpdate = $scope.editingTrip; - $window.cordova.plugins.BEMUserCache.putMessage(ConfirmHelper.inputDetails[inputType].key, $scope.draftInput).then(function () { - $scope.$apply(function() { - if (isOther) { - tripToUpdate.userInput[inputType] = ConfirmHelper.getFakeEntry(input.value); - $scope.inputParams[inputType].options.push(tripToUpdate.userInput[inputType]); - $scope.inputParams[inputType].value2entry[input.value] = tripToUpdate.userInput[inputType]; - } else { - tripToUpdate.userInput[inputType] = $scope.inputParams[inputType].value2entry[input.value]; - } - $scope.updateTripProperties(tripToUpdate); // Redo our inferences, filters, etc. based on this new information - }); - }); - if (isOther == true) - $scope.draftInput = angular.undefined; - } - $scope.redirect = function(){ $state.go("root.main.current"); }; diff --git a/www/js/tripconfirm/multi-label-ui.js b/www/js/tripconfirm/multi-label-ui.js index 8f37d9cf3..f1725e015 100644 --- a/www/js/tripconfirm/multi-label-ui.js +++ b/www/js/tripconfirm/multi-label-ui.js @@ -1,3 +1,17 @@ +/* + * Directive to display a set of configurable labels for each trip + * Assumptions: + * - The directive is embedded within an ion-view + * - The controller for the ion-view has a function called + * 'recomputeDisplayTrips` which modifies the trip *list* as necessary. An + * example with the label view is removing the labeled trips from the + * "toLabel" filter. Function can be a no-op (for example, in + * the diary view) + * - The view is associated with a state which we can record in the client stats. + * - The directive implements a `verifyTrip` function that can be invoked by + * other components. + */ + angular.module('emission.tripconfirm.multilabel', ['emission.tripconfirm.services', 'emission.stats.clientstats', @@ -7,6 +21,7 @@ angular.module('emission.tripconfirm.multilabel', scope: { trip: "=", unifiedConfirmsResults: "=", + manualResultMap: "=" }, controller: "MultiLabelCtrl", templateUrl: 'templates/tripconfirm/multi-label-ui.html' @@ -15,6 +30,27 @@ angular.module('emission.tripconfirm.multilabel', .controller("MultiLabelCtrl", function($scope, $element, $attrs, ConfirmHelper, $ionicPopover, $window, DiaryHelper, ClientStats) { console.log("Invoked multilabel directive controller for labels "+ConfirmHelper.INPUTS); + console.log("Invoked multilabel directive controller with manualResultMap "+JSON.stringify($scope.manualResultMap), $scope.manualResultMap); + + var findViewElement = function() { + console.log("$element is ", $element); + console.log("parent row is", $element.parents("ion-item")); + let rowElement = $element.parents("ion-view") + console.log("row Element is", rowElement); + return angular.element(rowElement); + } + + var findViewState = function() { + let viewState = findViewElement().attr("state") + console.log("view state is ", viewState); + return viewState; + } + + var findViewScope = function() { + let viewScope = findViewElement().scope(); + console.log("view scope is ", viewScope); + return viewScope; + } /** * BEGIN: Required external interface for all label directives @@ -28,15 +64,24 @@ angular.module('emission.tripconfirm.multilabel', * Side effect: verifies the trip (partially if needed) and updates the trip * verifiability status. */ + + /** + * verifyTrip turns all of a given trip's yellow labels green + */ $scope.verifyTrip = function() { console.log("About to verify trip "+$scope.trip.start_ts +" -> "+$scope.trip.end_ts+" with current visibility" + $scope.trip.verifiability); if ($scope.trip.verifiability != "can-verify") { - ClientStats.addReading(ClientStats.getStatKeys().VERIFY_TRIP, {"verifiable": false}); + ClientStats.addReading(ClientStats.getStatKeys().VERIFY_TRIP, + {"verifiable": false, "currView": $scope.currentViewState}); return; } - ClientStats.addReading(ClientStats.getStatKeys().VERIFY_TRIP, {"verifiable": true, "userInput": angular.toJson(trip.userInput), "finalInference": angular.toJson(trip.finalInference)}); + ClientStats.addReading(ClientStats.getStatKeys().VERIFY_TRIP, + {"verifiable": true, + "currView": $scope.currentViewState, + "userInput": angular.toJson(trip.userInput), + "finalInference": angular.toJson(trip.finalInference)}); $scope.draftInput = { "start_ts": trip.start_ts, @@ -56,7 +101,9 @@ angular.module('emission.tripconfirm.multilabel', */ /** - * Embed 'inputType' to the trip + * Embed 'inputType' to the trip. + * This is the version that is called from the diary, where the trips are + * geojson objects. We should unify this and populateManualInputs later. */ $scope.populateInputFromTimeline = function (trip, nextTripgj, inputType, inputList) { console.log("While populating inputs, inputParams", $scope.inputParams); @@ -64,20 +111,50 @@ angular.module('emission.tripconfirm.multilabel', if (angular.isDefined(userInput)) { // userInput is an object with data + metadata // the label is the "value" from the options - var userInputEntry = $scope.inputParams[inputType].value2entry[userInput.data.label]; - if (!angular.isDefined(userInputEntry)) { - userInputEntry = ConfirmHelper.getFakeEntry(userInput.data.label); - $scope.inputParams[inputType].options.push(userInputEntry); - $scope.inputParams[inputType].value2entry[userInput.data.label] = userInputEntry; - } - console.log("Mapped label "+userInput.data.label+" to entry "+JSON.stringify(userInputEntry)); - trip.userInput[inputType] = userInputEntry; + $scope.populateInput($scope.trip.userInput, inputType, userInput.data.label); } - Logger.log("Set "+ inputType + " " + JSON.stringify(userInputEntry) + " for trip id " + JSON.stringify(trip.data.id)); + // Logger.log("Set "+ inputType + " " + JSON.stringify(userInputEntry) + " for trip id " + JSON.stringify(trip.data.id)); $scope.editingTrip = angular.undefined; } - $scope.fillUserInputs = function() { + /** + * Embed 'inputType' to the trip + * This is the version that is called from the list, which focuses only on + * manual inputs. It also sets some additional values + */ + $scope.populateManualInputs = function (tripgj, nextTripgj, inputType, inputList) { + // Check unprocessed labels first since they are more recent + // Massage the input to meet getUserInputForTrip expectations + const unprocessedLabelEntry = DiaryHelper.getUserInputForTrip( + {data: {properties: tripgj, features: [{}, {}, {}]}}, + {data: {properties: nextTripgj, features: [{}, {}, {}]}}, + inputList); + var userInputLabel = unprocessedLabelEntry? unprocessedLabelEntry.data.label : undefined; + if (!angular.isDefined(userInputLabel)) { + userInputLabel = tripgj.user_input[$scope.inputType2retKey(inputType)]; + } + $scope.populateInput(tripgj.userInput, inputType, userInputLabel); + // Logger.log("Set "+ inputType + " " + JSON.stringify(userInputEntry) + " for trip starting at " + JSON.stringify(tripgj.start_fmt_time)); + $scope.editingTrip = angular.undefined; + } + + /** + * Insert the given userInputLabel into the given inputType's slot in inputField + */ + $scope.populateInput = function(tripField, inputType, userInputLabel) { + if (angular.isDefined(userInputLabel)) { + var userInputEntry = $scope.inputParams[inputType].value2entry[userInputLabel]; + if (!angular.isDefined(userInputEntry)) { + userInputEntry = ConfirmHelper.getFakeEntry(userInputLabel); + $scope.inputParams[inputType].options.push(userInputEntry); + $scope.inputParams[inputType].value2entry[userInputLabel] = userInputEntry; + } + console.log("Mapped label "+userInputLabel+" to entry "+JSON.stringify(userInputEntry)); + tripField[inputType] = userInputEntry; + } + } + + $scope.fillUserInputsGeojson = function() { console.log("Checking to fill user inputs for " +$scope.trip.display_start_time+" -> "+$scope.trip.display_end_time); if (angular.isDefined($scope.trip)) { @@ -93,23 +170,65 @@ angular.module('emission.tripconfirm.multilabel', } } + $scope.fillUserInputsObjects = function() { + if (angular.isDefined($scope.trip)) { + $scope.$apply(() => { + // console.log("Expectation: "+JSON.stringify(trip.expectation)); + // console.log("Inferred labels from server: "+JSON.stringify(trip.inferred_labels)); + $scope.trip.userInput = {}; + ConfirmHelper.INPUTS.forEach(function(item, index) { + $scope.populateManualInputs($scope.trip, $scope.trip.nextTrip, item, + $scope.manualResultMap[item]); + }); + $scope.trip.finalInference = {}; + $scope.inferFinalLabels($scope.trip); + $scope.updateVerifiability($scope.trip); + }); + } else { + console.log("Trip information not yet bound, skipping fill"); + } + } + + /* + * Note that we don't need to $watch for the unifiedConfirmsResults right now + * because we only start processing the trips after the confirms results are + * read. In other words, `$scope.data = Timeline.data;` sets both the trip + * wrappers and the confirmed results at the same time. But if we change that + * later, we should watch on that as well. + */ + $scope.$watch("trip", function(newVal, oldVal) { - console.log("the trip binding has changed from "+oldVal+" to new value "+newVal); + console.log("the trip binding has changed from ",oldVal," bo new value ",newVal); // We also launch this promise from the init. // If it is complete by the time the watch completes (the common case), the // promise will return immediately // but if the promise takes a while, we will still wait here until the data // is available. // Think of this as assert(inputParams) - if ($scope.unifiedConfirmsResults != undefined) { - ConfirmHelper.inputParamsPromise.then((inputParams) => { - $scope.inputParams = inputParams; - $scope.fillUserInputs(); - }); - console.log("After filling user inputs", $scope.trip); - } else { - console.log("No input list defined, skipping manual user input fill", $scope.unifiedConfirmsResults); + if ($scope.trip != undefined && + $scope.trip.data != undefined && + $scope.trip.data.properties.start_ts != undefined && + $scope.trip.start_ts == undefined) { + // Copy over the timestamps so that the entries have a somewhat similar format + // https://github.com/e-mission/e-mission-docs/issues/674#issuecomment-932833288 + $scope.trip.start_ts = $scope.trip.data.properties.start_ts; + $scope.trip.end_ts = $scope.trip.data.properties.end_ts; + console.log("This is a diary trip, after copying timestamps over ", $scope.trip); } + ConfirmHelper.inputParamsPromise.then((inputParams) => { + console.log("After reading input params, unifiedConfirmsResults ", + $scope.unifiedConfirmsResults, "manualResultMap", $scope.manualResultMap); + $scope.inputParams = inputParams; + if ($scope.unifiedConfirmsResults != undefined) { + $scope.fillUserInputsGeojson(); + console.log("After filling user inputs from the diary view", $scope.trip); + } else if ($scope.manualResultMap != undefined) { + $scope.fillUserInputsObjects(); + console.log("After filling user inputs from the label view", $scope.trip); + } else { + console.log("No input list defined, skipping manual user input fill", $scope.unifiedConfirmsResults); + } + }); }); $scope.popovers = {}; @@ -130,8 +249,8 @@ angular.module('emission.tripconfirm.multilabel', $scope.selected[inputType].value = ''; } $scope.draftInput = { - "start_ts": trip.data.properties.start_ts, - "end_ts": trip.data.properties.end_ts + "start_ts": trip.start_ts, + "end_ts": trip.end_ts }; $scope.editingTrip = trip; Logger.log("in openPopover, setting draftInput = " + JSON.stringify($scope.draftInput)); @@ -174,6 +293,13 @@ angular.module('emission.tripconfirm.multilabel', }; $scope.choose = function (inputType) { + ClientStats.addReading(ClientStats.getStatKeys().SELECT_LABEL, { + "userInput": angular.toJson($scope.editingTrip.userInput), + "finalInference": angular.toJson($scope.editingTrip.finalInference), + "currView": $scope.currentViewState, + "inputKey": inputType, + "inputVal": $scope.selected[inputType].value + }); var isOther = false if ($scope.selected[inputType].value != "other") { $scope.store(inputType, $scope.selected[inputType], isOther); @@ -202,13 +328,133 @@ angular.module('emission.tripconfirm.multilabel', } else { tripToUpdate.userInput[inputType] = $scope.inputParams[inputType].value2entry[input.value]; } + $scope.updateTripProperties(tripToUpdate); // Redo our inferences, filters, etc. based on this new information }); }); if (isOther == true) $scope.draftInput = angular.undefined; } + $scope.updateTripProperties = function(trip) { + $scope.inferFinalLabels(trip); + $scope.updateVerifiability(trip); + $scope.updateVisibilityAfterDelay(trip); + } + + /** + * Given the list of possible label tuples we've been sent and what the user has already input for the trip, choose the best labels to actually present to the user. + * The algorithm below operationalizes these principles: + * - Never consider label tuples that contradict a green label + * - Obey "conservation of uncertainty": the sum of probabilities after filtering by green labels must equal the sum of probabilities before + * - After filtering, predict the most likely choices at the level of individual labels, not label tuples + * - Never show user yellow labels that have a lower probability of being correct than confidenceThreshold + */ + $scope.inferFinalLabels = function(trip) { + // Deep copy the possibility tuples + let labelsList = []; + if (angular.isDefined(trip.inferred_labels)) { + labelsList = JSON.parse(JSON.stringify(trip.inferred_labels)); + } + + // Capture the level of certainty so we can reconstruct it later + const totalCertainty = labelsList.map(item => item.p).reduce(((item, rest) => item + rest), 0); + + // Filter out the tuples that are inconsistent with existing green labels + for (const inputType of ConfirmHelper.INPUTS) { + const userInput = trip.userInput[inputType]; + if (userInput) { + const retKey = $scope.inputType2retKey(inputType); + labelsList = labelsList.filter(item => item.labels[retKey] == userInput.value); + } + } + + // Red labels if we have no possibilities left + if (labelsList.length == 0) { + for (const inputType of ConfirmHelper.INPUTS) $scope.populateInput(trip.finalInference, inputType, undefined); + } + else { + // Normalize probabilities to previous level of certainty + const certaintyScalar = totalCertainty/labelsList.map(item => item.p).reduce((item, rest) => item + rest); + labelsList.forEach(item => item.p*=certaintyScalar); + + for (const inputType of ConfirmHelper.INPUTS) { + // For each label type, find the most probable value by binning by label value and summing + const retKey = $scope.inputType2retKey(inputType); + let valueProbs = new Map(); + for (const tuple of labelsList) { + const labelValue = tuple.labels[retKey]; + if (!valueProbs.has(labelValue)) valueProbs.set(labelValue, 0); + valueProbs.set(labelValue, valueProbs.get(labelValue) + tuple.p); + } + let max = {p: 0, labelValue: undefined}; + for (const [thisLabelValue, thisP] of valueProbs) { + // In the case of a tie, keep the label with earlier first appearance in the labelsList (we used a Map to preserve this order) + if (thisP > max.p) max = {p: thisP, labelValue: thisLabelValue}; + } + + // Display a label as red if its most probable inferred value has a probability less than or equal to the trip's confidence_threshold + // Fails safe if confidence_threshold doesn't exist + if (max.p <= trip.confidence_threshold) max.labelValue = undefined; + + $scope.populateInput(trip.finalInference, inputType, max.labelValue); + } + } + } + + /** + * MODE (becomes manual/mode_confirm) becomes mode_confirm + */ + $scope.inputType2retKey = function(inputType) { + return ConfirmHelper.inputDetails[inputType].key.split("/")[1]; + } + + /** + * For a given trip, compute how the "verify" button should behave. + * If the trip has at least one yellow label, the button should be clickable. + * If the trip has all green labels, the button should be disabled because everything has already been verified. + * If the trip has all red labels or a mix of red and green, the button should be disabled because we need more detailed user input. + */ + $scope.updateVerifiability = function(trip) { + var allGreen = true; + var someYellow = false; + for (const inputType of ConfirmHelper.INPUTS) { + const green = trip.userInput[inputType]; + const yellow = trip.finalInference[inputType] && !green; + if (yellow) someYellow = true; + if (!green) allGreen = false; + } + trip.verifiability = someYellow ? "can-verify" : (allGreen ? "already-verified" : "cannot-verify"); + } + + /* + * Embody the logic for delayed update: + * the recompute logic already keeps trips that are waitingForModification + * even if they would be filtered otherwise. + * so here: + * - set the trip as waiting for potential modifications + * - create a one minute timeout that will remove the wait and recompute + * - clear the existing timeout (if any) + */ + $scope.updateVisibilityAfterDelay = function(trip) { + // We have just edited this trip, and are now waiting to see if the user + // is going to modify it further + trip.waitingForMod = true; + let currTimeoutPromise = trip.timeoutPromise; + let THIRTY_SECS = 30 * 1000; + Logger.log("trip starting at "+trip.start_fmt_time+": creating new timeout"); + trip.timeoutPromise = $timeout(function() { + Logger.log("trip starting at "+trip.start_fmt_time+": executing recompute"); + trip.waitingForMod = false; + trip.timeoutPromise = undefined; + let viewScope = findViewScope(); + viewScope.recomputeDisplayTrips(); + }, THIRTY_SECS); + Logger.log("trip starting at "+trip.start_fmt_time+": cancelling existing timeout "+currTimeoutPromise); + $timeout.cancel(currTimeoutPromise); + } + $scope.init = function() { + console.log("During initialization, trip is ", $scope.trip); $scope.userInputDetails = []; ConfirmHelper.INPUTS.forEach(function(item, index) { const currInput = angular.copy(ConfirmHelper.inputDetails[item]); @@ -217,6 +463,7 @@ angular.module('emission.tripconfirm.multilabel', }); ConfirmHelper.inputParamsPromise.then((inputParams) => $scope.inputParams = inputParams); console.log("Finished initializing directive, userInputDetails = ", $scope.userInputDetails); + $scope.currViewState = findViewState(); } $scope.init(); diff --git a/www/templates/diary/infinite_scroll_list.html b/www/templates/diary/infinite_scroll_list.html index a9cf24bf7..f6a16f771 100644 --- a/www/templates/diary/infinite_scroll_list.html +++ b/www/templates/diary/infinite_scroll_list.html @@ -72,11 +72,12 @@

{{'diary.scroll-to-load-more' | transla {{trip.end_display_name}}

-
- +
diff --git a/www/templates/diary/list.html b/www/templates/diary/list.html index ac16d96cb..22cb2ff61 100644 --- a/www/templates/diary/list.html +++ b/www/templates/diary/list.html @@ -92,7 +92,8 @@
- +
From 8bc51850e1c8df22119a2bc8d2ad7a1b3d787e1a Mon Sep 17 00:00:00 2001 From: Shankari Date: Sun, 3 Oct 2021 19:43:38 -0700 Subject: [PATCH 015/175] Remove view controller's dependency on one specfic set of filters Inject the filtering factory dynamically Remove the static dependency Initialize the selected filters from the factory This addresses https://github.com/e-mission/e-mission-docs/issues/674#issuecomment-933094153 --- www/js/diary/infinite_scroll_filters.js | 9 +++++---- www/js/diary/infinite_scroll_list.js | 13 +++++-------- www/js/tripconfirm/multi-label-ui.js | 2 +- 3 files changed, 11 insertions(+), 13 deletions(-) diff --git a/www/js/diary/infinite_scroll_filters.js b/www/js/diary/infinite_scroll_filters.js index 1f441b330..ec57a4ee0 100644 --- a/www/js/diary/infinite_scroll_filters.js +++ b/www/js/diary/infinite_scroll_filters.js @@ -39,10 +39,6 @@ angular.module('emission.main.diary.infscrollfilters',[ } } - sf.waitingForMod = function(t) { - return t.waitingForMod == true; - } - sf.UNLABELED = { key: "unlabeled", text: $translate.instant(".unlabeled"), @@ -62,5 +58,10 @@ angular.module('emission.main.diary.infscrollfilters',[ filter: toLabelCheck, width: "col-50" } + + sf.configuredFilters = [ + sf.TO_LABEL, + sf.UNLABELED + ]; return sf; }); diff --git a/www/js/diary/infinite_scroll_list.js b/www/js/diary/infinite_scroll_list.js index 4480d8129..f2ff0fcdf 100644 --- a/www/js/diary/infinite_scroll_list.js +++ b/www/js/diary/infinite_scroll_list.js @@ -20,14 +20,14 @@ angular.module('emission.main.diary.infscrolllist',['ui-leaflet', 'emission.stats.clientstats', 'emission.plugin.logger']) -.controller("InfiniteDiaryListCtrl", function($window, $scope, $rootScope, $ionicPlatform, $state, +.controller("InfiniteDiaryListCtrl", function($window, $scope, $rootScope, $injector, + $ionicPlatform, $state, $ionicScrollDelegate, $ionicPopup, ClientStats, $ionicLoading, $ionicActionSheet, $timeout, ionicDatePicker, leafletData, Timeline, CommonGraph, DiaryHelper, - InfScrollFilters, Config, PostTripManualMarker, nzTour, KVStore, Logger, UnifiedDataLoader, $ionicPopover, $ionicModal, $translate, $q) { // TODO: load only a subset of entries instead of everything @@ -38,15 +38,12 @@ angular.module('emission.main.diary.infscrolllist',['ui-leaflet', const placeLimiter = new Bottleneck({ maxConcurrent: 2, minTime: 500 }); $scope.data = {}; + $scope.tripFilterFactory = $injector.get("InfScrollFilters"); + $scope.filterInputs = $scope.tripFilterFactory.configuredFilters; $scope.getActiveFilters = function() { return $scope.filterInputs.filter(sf => sf.state).map(sf => sf.key); } - // reset all filters - $scope.filterInputs = [ - InfScrollFilters.TO_LABEL, - InfScrollFilters.UNLABELED - ]; $scope.filterInputs.forEach((f) => { f.state = false; }); @@ -227,7 +224,7 @@ angular.module('emission.main.diary.infscrolllist',['ui-leaflet', } else { // console.log("Trip n before: "+$scope.data.displayTrips.length); $scope.data.displayTrips = $scope.data.allTrips.filter( - t => InfScrollFilters.waitingForMod(t) || f.filter(t)); + t => (t.waitingForMod == true) || f.filter(t)); // console.log("Trip n after: "+$scope.data.displayTrips.length); alreadyFiltered = true; } diff --git a/www/js/tripconfirm/multi-label-ui.js b/www/js/tripconfirm/multi-label-ui.js index f1725e015..58853835e 100644 --- a/www/js/tripconfirm/multi-label-ui.js +++ b/www/js/tripconfirm/multi-label-ui.js @@ -27,7 +27,7 @@ angular.module('emission.tripconfirm.multilabel', templateUrl: 'templates/tripconfirm/multi-label-ui.html' }; }) -.controller("MultiLabelCtrl", function($scope, $element, $attrs, +.controller("MultiLabelCtrl", function($scope, $element, $attrs, $timeout, ConfirmHelper, $ionicPopover, $window, DiaryHelper, ClientStats) { console.log("Invoked multilabel directive controller for labels "+ConfirmHelper.INPUTS); console.log("Invoked multilabel directive controller with manualResultMap "+JSON.stringify($scope.manualResultMap), $scope.manualResultMap); From b382b8ff21809a920dee8159da1aa94e5a70bd83 Mon Sep 17 00:00:00 2001 From: Shankari Date: Mon, 4 Oct 2021 11:33:34 -0700 Subject: [PATCH 016/175] Pull the populate code out into a service Pull out all the populateXXX and recalculateXXX functionality into a separate service so it can be invoked from multiple controllers. This is consistent with https://github.com/e-mission/e-mission-docs/issues/674#issuecomment-933083710 We load the service dynamically to reduce the hardcoded dependency issue. We retain a couple of simple wrappers e.g. `fillUserInputsGeojson` in the controller so that we can invoke it from `$watch` more easily and we can call `$scope.$apply` to update the visualization. Remove references to `scope.manualResultMap` from the controller since the expanded values will be pre-populated. Pass the viewScope around as needed to support the callback after the update. Add a new NOP callback to the diary view to match the desired external interface. Add blank inferred label datastructures for the diary pending a bigger restructuring that will send inferred labels to as part of the geojson. --- www/js/diary/infinite_scroll_list.js | 3 + www/js/diary/list.js | 4 + www/js/tripconfirm/multi-label-ui.js | 218 ++++++++++-------- www/templates/diary/infinite_scroll_list.html | 7 +- 4 files changed, 131 insertions(+), 101 deletions(-) diff --git a/www/js/diary/infinite_scroll_list.js b/www/js/diary/infinite_scroll_list.js index f2ff0fcdf..e64d942bf 100644 --- a/www/js/diary/infinite_scroll_list.js +++ b/www/js/diary/infinite_scroll_list.js @@ -41,6 +41,8 @@ angular.module('emission.main.diary.infscrolllist',['ui-leaflet', $scope.tripFilterFactory = $injector.get("InfScrollFilters"); $scope.filterInputs = $scope.tripFilterFactory.configuredFilters; + $scope.labelPopulateFactory = $injector.get("MultiLabelService"); + $scope.getActiveFilters = function() { return $scope.filterInputs.filter(sf => sf.state).map(sf => sf.key); } @@ -97,6 +99,7 @@ angular.module('emission.main.diary.infscrolllist',['ui-leaflet', ctList.forEach($scope.populateBasicClasses); ctList.forEach((trip, tIndex) => { trip.nextTrip = ctList[tIndex+1]; + $scope.labelPopulateFactory.populateInputsAndInferences(trip, $scope.data.manualResultMap); }); // Fill places on a reversed copy of the list so we fill from the bottom up ctList.slice().reverse().forEach(function(trip, index) { diff --git a/www/js/diary/list.js b/www/js/diary/list.js index 26609edaf..2a7fe0be3 100644 --- a/www/js/diary/list.js +++ b/www/js/diary/list.js @@ -459,6 +459,10 @@ angular.module('emission.main.diary.list',['ui-leaflet', }); }; + $scope.recomputeDisplayTrips = function() { + console.log("recomputing is a NOP on the diary since we always show all trips"); + }; + $ionicPlatform.ready().then(function() { readAndUpdateForDay(moment().startOf('day')); diff --git a/www/js/tripconfirm/multi-label-ui.js b/www/js/tripconfirm/multi-label-ui.js index 58853835e..27a0b543e 100644 --- a/www/js/tripconfirm/multi-label-ui.js +++ b/www/js/tripconfirm/multi-label-ui.js @@ -21,16 +21,14 @@ angular.module('emission.tripconfirm.multilabel', scope: { trip: "=", unifiedConfirmsResults: "=", - manualResultMap: "=" }, controller: "MultiLabelCtrl", templateUrl: 'templates/tripconfirm/multi-label-ui.html' }; }) -.controller("MultiLabelCtrl", function($scope, $element, $attrs, $timeout, - ConfirmHelper, $ionicPopover, $window, DiaryHelper, ClientStats) { +.controller("MultiLabelCtrl", function($scope, $element, $attrs, + ConfirmHelper, $ionicPopover, $window, ClientStats, MultiLabelService) { console.log("Invoked multilabel directive controller for labels "+ConfirmHelper.INPUTS); - console.log("Invoked multilabel directive controller with manualResultMap "+JSON.stringify($scope.manualResultMap), $scope.manualResultMap); var findViewElement = function() { console.log("$element is ", $element); @@ -100,60 +98,6 @@ angular.module('emission.tripconfirm.multilabel', * END: Required external interface for all label directives */ - /** - * Embed 'inputType' to the trip. - * This is the version that is called from the diary, where the trips are - * geojson objects. We should unify this and populateManualInputs later. - */ - $scope.populateInputFromTimeline = function (trip, nextTripgj, inputType, inputList) { - console.log("While populating inputs, inputParams", $scope.inputParams); - var userInput = DiaryHelper.getUserInputForTrip(trip, nextTripgj, inputList); - if (angular.isDefined(userInput)) { - // userInput is an object with data + metadata - // the label is the "value" from the options - $scope.populateInput($scope.trip.userInput, inputType, userInput.data.label); - } - // Logger.log("Set "+ inputType + " " + JSON.stringify(userInputEntry) + " for trip id " + JSON.stringify(trip.data.id)); - $scope.editingTrip = angular.undefined; - } - - /** - * Embed 'inputType' to the trip - * This is the version that is called from the list, which focuses only on - * manual inputs. It also sets some additional values - */ - $scope.populateManualInputs = function (tripgj, nextTripgj, inputType, inputList) { - // Check unprocessed labels first since they are more recent - // Massage the input to meet getUserInputForTrip expectations - const unprocessedLabelEntry = DiaryHelper.getUserInputForTrip( - {data: {properties: tripgj, features: [{}, {}, {}]}}, - {data: {properties: nextTripgj, features: [{}, {}, {}]}}, - inputList); - var userInputLabel = unprocessedLabelEntry? unprocessedLabelEntry.data.label : undefined; - if (!angular.isDefined(userInputLabel)) { - userInputLabel = tripgj.user_input[$scope.inputType2retKey(inputType)]; - } - $scope.populateInput(tripgj.userInput, inputType, userInputLabel); - // Logger.log("Set "+ inputType + " " + JSON.stringify(userInputEntry) + " for trip starting at " + JSON.stringify(tripgj.start_fmt_time)); - $scope.editingTrip = angular.undefined; - } - - /** - * Insert the given userInputLabel into the given inputType's slot in inputField - */ - $scope.populateInput = function(tripField, inputType, userInputLabel) { - if (angular.isDefined(userInputLabel)) { - var userInputEntry = $scope.inputParams[inputType].value2entry[userInputLabel]; - if (!angular.isDefined(userInputEntry)) { - userInputEntry = ConfirmHelper.getFakeEntry(userInputLabel); - $scope.inputParams[inputType].options.push(userInputEntry); - $scope.inputParams[inputType].value2entry[userInputLabel] = userInputEntry; - } - console.log("Mapped label "+userInputLabel+" to entry "+JSON.stringify(userInputEntry)); - tripField[inputType] = userInputEntry; - } - } - $scope.fillUserInputsGeojson = function() { console.log("Checking to fill user inputs for " +$scope.trip.display_start_time+" -> "+$scope.trip.display_end_time); @@ -161,7 +105,7 @@ angular.module('emission.tripconfirm.multilabel', $scope.$apply(() => { $scope.trip.userInput = {}; ConfirmHelper.INPUTS.forEach(function(item, index) { - $scope.populateInputFromTimeline($scope.trip, $scope.trip.nextTripgj, + MultiLabelService.populateInputFromTimeline($scope.trip, $scope.trip.nextTripgj, item, $scope.unifiedConfirmsResults[item]); }); }); @@ -170,19 +114,17 @@ angular.module('emission.tripconfirm.multilabel', } } + $scope.fillUserInputsObjects = function() { + console.log("Checking to fill user inputs for " + +$scope.trip.display_start_time+" -> "+$scope.trip.display_end_time); if (angular.isDefined($scope.trip)) { $scope.$apply(() => { - // console.log("Expectation: "+JSON.stringify(trip.expectation)); - // console.log("Inferred labels from server: "+JSON.stringify(trip.inferred_labels)); $scope.trip.userInput = {}; ConfirmHelper.INPUTS.forEach(function(item, index) { - $scope.populateManualInputs($scope.trip, $scope.trip.nextTrip, item, - $scope.manualResultMap[item]); + MultiLabelService.populateManualInputs($scope.trip, $scope.trip.nextTripgj, + item, $scope.unifiedConfirmsResults[item]); }); - $scope.trip.finalInference = {}; - $scope.inferFinalLabels($scope.trip); - $scope.updateVerifiability($scope.trip); }); } else { console.log("Trip information not yet bound, skipping fill"); @@ -213,18 +155,17 @@ angular.module('emission.tripconfirm.multilabel', // https://github.com/e-mission/e-mission-docs/issues/674#issuecomment-932833288 $scope.trip.start_ts = $scope.trip.data.properties.start_ts; $scope.trip.end_ts = $scope.trip.data.properties.end_ts; + $scope.trip.inferred_labels = []; + $scope.trip.finalInference = {}; console.log("This is a diary trip, after copying timestamps over ", $scope.trip); } ConfirmHelper.inputParamsPromise.then((inputParams) => { console.log("After reading input params, unifiedConfirmsResults ", - $scope.unifiedConfirmsResults, "manualResultMap", $scope.manualResultMap); + $scope.unifiedConfirmsResults); $scope.inputParams = inputParams; if ($scope.unifiedConfirmsResults != undefined) { $scope.fillUserInputsGeojson(); console.log("After filling user inputs from the diary view", $scope.trip); - } else if ($scope.manualResultMap != undefined) { - $scope.fillUserInputsObjects(); - console.log("After filling user inputs from the label view", $scope.trip); } else { console.log("No input list defined, skipping manual user input fill", $scope.unifiedConfirmsResults); } @@ -264,6 +205,7 @@ angular.module('emission.tripconfirm.multilabel', $scope.popovers[inputType].hide(); }; + /** * Store selected value for options * $scope.selected is for display only @@ -328,19 +270,111 @@ angular.module('emission.tripconfirm.multilabel', } else { tripToUpdate.userInput[inputType] = $scope.inputParams[inputType].value2entry[input.value]; } - $scope.updateTripProperties(tripToUpdate); // Redo our inferences, filters, etc. based on this new information + let viewScope = findViewScope(); + MultiLabelService.updateTripProperties(tripToUpdate, viewScope); // Redo our inferences, filters, etc. based on this new information }); }); if (isOther == true) $scope.draftInput = angular.undefined; } - $scope.updateTripProperties = function(trip) { - $scope.inferFinalLabels(trip); - $scope.updateVerifiability(trip); - $scope.updateVisibilityAfterDelay(trip); + $scope.init = function() { + console.log("During initialization, trip is ", $scope.trip); + $scope.userInputDetails = []; + ConfirmHelper.INPUTS.forEach(function(item, index) { + const currInput = angular.copy(ConfirmHelper.inputDetails[item]); + currInput.name = item; + $scope.userInputDetails.push(currInput); + }); + ConfirmHelper.inputParamsPromise.then((inputParams) => $scope.inputParams = inputParams); + console.log("Finished initializing directive, userInputDetails = ", $scope.userInputDetails); + $scope.currViewState = findViewState(); } + $scope.init(); +}) +.factory("MultiLabelService", function(ConfirmHelper, DiaryHelper, $timeout) { + var mls = {}; + + ConfirmHelper.inputParamsPromise.then((inputParams) => mls.inputParams = inputParams); + + /** + * Embed 'inputType' to the trip. + * This is the version that is called from the diary, where the trips are + * geojson objects. We should unify this and populateManualInputs later. + */ + mls.populateInputFromTimeline = function (trip, nextTripgj, inputType, inputList) { + console.log("While populating inputs, inputParams", mls.inputParams); + var userInput = DiaryHelper.getUserInputForTrip(trip, nextTripgj, inputList); + if (angular.isDefined(userInput)) { + // userInput is an object with data + metadata + // the label is the "value" from the options + mls.populateInput(trip.userInput, inputType, userInput.data.label); + } + // Logger.log("Set "+ inputType + " " + JSON.stringify(userInputEntry) + " for trip id " + JSON.stringify(trip.data.id)); + mls.editingTrip = angular.undefined; + } + + mls.populateInputsAndInferences = function(trip, manualResultMap) { + if (angular.isDefined(trip)) { + // console.log("Expectation: "+JSON.stringify(trip.expectation)); + // console.log("Inferred labels from server: "+JSON.stringify(trip.inferred_labels)); + trip.userInput = {}; + ConfirmHelper.INPUTS.forEach(function(item, index) { + mls.populateManualInputs(trip, trip.nextTrip, item, + manualResultMap[item]); + }); + trip.finalInference = {}; + mls.inferFinalLabels(trip); + mls.updateVerifiability(trip); + } else { + console.log("Trip information not yet bound, skipping fill"); + } + } + + /** + * Embed 'inputType' to the trip + * This is the version that is called from the list, which focuses only on + * manual inputs. It also sets some additional values + */ + mls.populateManualInputs = function (tripgj, nextTripgj, inputType, inputList) { + // Check unprocessed labels first since they are more recent + // Massage the input to meet getUserInputForTrip expectations + const unprocessedLabelEntry = DiaryHelper.getUserInputForTrip( + {data: {properties: tripgj, features: [{}, {}, {}]}}, + {data: {properties: nextTripgj, features: [{}, {}, {}]}}, + inputList); + var userInputLabel = unprocessedLabelEntry? unprocessedLabelEntry.data.label : undefined; + if (!angular.isDefined(userInputLabel)) { + userInputLabel = tripgj.user_input[mls.inputType2retKey(inputType)]; + } + mls.populateInput(tripgj.userInput, inputType, userInputLabel); + // Logger.log("Set "+ inputType + " " + JSON.stringify(userInputEntry) + " for trip starting at " + JSON.stringify(tripgj.start_fmt_time)); + mls.editingTrip = angular.undefined; + } + + /** + * Insert the given userInputLabel into the given inputType's slot in inputField + */ + mls.populateInput = function(tripField, inputType, userInputLabel) { + if (angular.isDefined(userInputLabel)) { + var userInputEntry = mls.inputParams[inputType].value2entry[userInputLabel]; + if (!angular.isDefined(userInputEntry)) { + userInputEntry = ConfirmHelper.getFakeEntry(userInputLabel); + mls.inputParams[inputType].options.push(userInputEntry); + mls.inputParams[inputType].value2entry[userInputLabel] = userInputEntry; + } + console.log("Mapped label "+userInputLabel+" to entry "+JSON.stringify(userInputEntry)); + tripField[inputType] = userInputEntry; + } + } + + + mls.updateTripProperties = function(trip, viewScope) { + mls.inferFinalLabels(trip); + mls.updateVerifiability(trip); + mls.updateVisibilityAfterDelay(trip, viewScope); + } /** * Given the list of possible label tuples we've been sent and what the user has already input for the trip, choose the best labels to actually present to the user. * The algorithm below operationalizes these principles: @@ -349,7 +383,7 @@ angular.module('emission.tripconfirm.multilabel', * - After filtering, predict the most likely choices at the level of individual labels, not label tuples * - Never show user yellow labels that have a lower probability of being correct than confidenceThreshold */ - $scope.inferFinalLabels = function(trip) { + mls.inferFinalLabels = function(trip) { // Deep copy the possibility tuples let labelsList = []; if (angular.isDefined(trip.inferred_labels)) { @@ -363,14 +397,14 @@ angular.module('emission.tripconfirm.multilabel', for (const inputType of ConfirmHelper.INPUTS) { const userInput = trip.userInput[inputType]; if (userInput) { - const retKey = $scope.inputType2retKey(inputType); + const retKey = mls.inputType2retKey(inputType); labelsList = labelsList.filter(item => item.labels[retKey] == userInput.value); } } // Red labels if we have no possibilities left if (labelsList.length == 0) { - for (const inputType of ConfirmHelper.INPUTS) $scope.populateInput(trip.finalInference, inputType, undefined); + for (const inputType of ConfirmHelper.INPUTS) mls.populateInput(trip.finalInference, inputType, undefined); } else { // Normalize probabilities to previous level of certainty @@ -379,7 +413,7 @@ angular.module('emission.tripconfirm.multilabel', for (const inputType of ConfirmHelper.INPUTS) { // For each label type, find the most probable value by binning by label value and summing - const retKey = $scope.inputType2retKey(inputType); + const retKey = mls.inputType2retKey(inputType); let valueProbs = new Map(); for (const tuple of labelsList) { const labelValue = tuple.labels[retKey]; @@ -396,7 +430,7 @@ angular.module('emission.tripconfirm.multilabel', // Fails safe if confidence_threshold doesn't exist if (max.p <= trip.confidence_threshold) max.labelValue = undefined; - $scope.populateInput(trip.finalInference, inputType, max.labelValue); + mls.populateInput(trip.finalInference, inputType, max.labelValue); } } } @@ -404,7 +438,7 @@ angular.module('emission.tripconfirm.multilabel', /** * MODE (becomes manual/mode_confirm) becomes mode_confirm */ - $scope.inputType2retKey = function(inputType) { + mls.inputType2retKey = function(inputType) { return ConfirmHelper.inputDetails[inputType].key.split("/")[1]; } @@ -414,7 +448,7 @@ angular.module('emission.tripconfirm.multilabel', * If the trip has all green labels, the button should be disabled because everything has already been verified. * If the trip has all red labels or a mix of red and green, the button should be disabled because we need more detailed user input. */ - $scope.updateVerifiability = function(trip) { + mls.updateVerifiability = function(trip) { var allGreen = true; var someYellow = false; for (const inputType of ConfirmHelper.INPUTS) { @@ -435,7 +469,7 @@ angular.module('emission.tripconfirm.multilabel', * - create a one minute timeout that will remove the wait and recompute * - clear the existing timeout (if any) */ - $scope.updateVisibilityAfterDelay = function(trip) { + mls.updateVisibilityAfterDelay = function(trip, viewScope) { // We have just edited this trip, and are now waiting to see if the user // is going to modify it further trip.waitingForMod = true; @@ -446,25 +480,11 @@ angular.module('emission.tripconfirm.multilabel', Logger.log("trip starting at "+trip.start_fmt_time+": executing recompute"); trip.waitingForMod = false; trip.timeoutPromise = undefined; - let viewScope = findViewScope(); + console.log("Recomputing display trips on ", viewScope); viewScope.recomputeDisplayTrips(); }, THIRTY_SECS); Logger.log("trip starting at "+trip.start_fmt_time+": cancelling existing timeout "+currTimeoutPromise); $timeout.cancel(currTimeoutPromise); } - - $scope.init = function() { - console.log("During initialization, trip is ", $scope.trip); - $scope.userInputDetails = []; - ConfirmHelper.INPUTS.forEach(function(item, index) { - const currInput = angular.copy(ConfirmHelper.inputDetails[item]); - currInput.name = item; - $scope.userInputDetails.push(currInput); - }); - ConfirmHelper.inputParamsPromise.then((inputParams) => $scope.inputParams = inputParams); - console.log("Finished initializing directive, userInputDetails = ", $scope.userInputDetails); - $scope.currViewState = findViewState(); - } - - $scope.init(); + return mls; }); diff --git a/www/templates/diary/infinite_scroll_list.html b/www/templates/diary/infinite_scroll_list.html index f6a16f771..f950c85f7 100644 --- a/www/templates/diary/infinite_scroll_list.html +++ b/www/templates/diary/infinite_scroll_list.html @@ -76,8 +76,11 @@

{{'diary.scroll-to-load-more' | transla class="col-10 diarycheckmark-container center-vert center-horiz">
- + +
From 5074b4ec58044c187bdddc309a12f4165a5dd5db Mon Sep 17 00:00:00 2001 From: Shankari Date: Mon, 4 Oct 2021 12:26:30 -0700 Subject: [PATCH 017/175] Address performance issue by pre-populating and removing the directive `$watch` Add a simple wrapper (`populateInputsDummyInferences`) to the service to iterate over all the inputs and populate them, similar to the existing `populateInputsAndInferences`. This is consistent with https://github.com/e-mission/e-mission-docs/issues/674#issuecomment-933771269 Dynamically inject the service in the diary as well Call the new method while filling in other fields Move the code to try and unify the trip structure to the new function as well Testing done: Scrolled through the diary and list views, do not see any performance degradation --- www/js/diary/list.js | 5 +- www/js/tripconfirm/multi-label-ui.js | 79 ++++++++-------------------- 2 files changed, 25 insertions(+), 59 deletions(-) diff --git a/www/js/diary/list.js b/www/js/diary/list.js index 2a7fe0be3..38f7ae90d 100644 --- a/www/js/diary/list.js +++ b/www/js/diary/list.js @@ -19,7 +19,8 @@ angular.module('emission.main.diary.list',['ui-leaflet', 'emission.plugin.logger' ]) -.controller("DiaryListCtrl", function($window, $scope, $rootScope, $ionicPlatform, $state, +.controller("DiaryListCtrl", function($window, $scope, $rootScope, $injector, + $ionicPlatform, $state, $ionicScrollDelegate, $ionicPopup, $ionicLoading, $ionicActionSheet, @@ -28,6 +29,7 @@ angular.module('emission.main.diary.list',['ui-leaflet', Config, PostTripManualMarker, nzTour, KVStore, Logger, UnifiedDataLoader, $ionicPopover, $translate) { console.log("controller DiaryListCtrl called"); // Add option + $scope.labelPopulateFactory = $injector.get("MultiLabelService"); $scope.$on('leafletDirectiveMap.resize', function(event, data) { console.log("diary/list received resize event, invalidating map size"); @@ -214,6 +216,7 @@ angular.module('emission.main.diary.list',['ui-leaflet', // Add "next" pointers to make it easier to use trip linkages for display $scope.data.currDayTripWrappers.forEach(function(tripgj, tripIndex, array) { tripgj.nextTripgj = array[tripIndex+1]; + $scope.labelPopulateFactory.populateInputsDummyInferences(tripgj, $scope.data.unifiedConfirmsResults); $scope.populateBasicClasses(tripgj); $scope.populateCommonInfo(tripgj); }); diff --git a/www/js/tripconfirm/multi-label-ui.js b/www/js/tripconfirm/multi-label-ui.js index 27a0b543e..54a167f90 100644 --- a/www/js/tripconfirm/multi-label-ui.js +++ b/www/js/tripconfirm/multi-label-ui.js @@ -114,64 +114,6 @@ angular.module('emission.tripconfirm.multilabel', } } - - $scope.fillUserInputsObjects = function() { - console.log("Checking to fill user inputs for " - +$scope.trip.display_start_time+" -> "+$scope.trip.display_end_time); - if (angular.isDefined($scope.trip)) { - $scope.$apply(() => { - $scope.trip.userInput = {}; - ConfirmHelper.INPUTS.forEach(function(item, index) { - MultiLabelService.populateManualInputs($scope.trip, $scope.trip.nextTripgj, - item, $scope.unifiedConfirmsResults[item]); - }); - }); - } else { - console.log("Trip information not yet bound, skipping fill"); - } - } - - /* - * Note that we don't need to $watch for the unifiedConfirmsResults right now - * because we only start processing the trips after the confirms results are - * read. In other words, `$scope.data = Timeline.data;` sets both the trip - * wrappers and the confirmed results at the same time. But if we change that - * later, we should watch on that as well. - */ - - $scope.$watch("trip", function(newVal, oldVal) { - console.log("the trip binding has changed from ",oldVal," bo new value ",newVal); - // We also launch this promise from the init. - // If it is complete by the time the watch completes (the common case), the - // promise will return immediately - // but if the promise takes a while, we will still wait here until the data - // is available. - // Think of this as assert(inputParams) - if ($scope.trip != undefined && - $scope.trip.data != undefined && - $scope.trip.data.properties.start_ts != undefined && - $scope.trip.start_ts == undefined) { - // Copy over the timestamps so that the entries have a somewhat similar format - // https://github.com/e-mission/e-mission-docs/issues/674#issuecomment-932833288 - $scope.trip.start_ts = $scope.trip.data.properties.start_ts; - $scope.trip.end_ts = $scope.trip.data.properties.end_ts; - $scope.trip.inferred_labels = []; - $scope.trip.finalInference = {}; - console.log("This is a diary trip, after copying timestamps over ", $scope.trip); - } - ConfirmHelper.inputParamsPromise.then((inputParams) => { - console.log("After reading input params, unifiedConfirmsResults ", - $scope.unifiedConfirmsResults); - $scope.inputParams = inputParams; - if ($scope.unifiedConfirmsResults != undefined) { - $scope.fillUserInputsGeojson(); - console.log("After filling user inputs from the diary view", $scope.trip); - } else { - console.log("No input list defined, skipping manual user input fill", $scope.unifiedConfirmsResults); - } - }); - }); - $scope.popovers = {}; ConfirmHelper.INPUTS.forEach(function(item, index) { let popoverPath = 'templates/diary/'+item.toLowerCase()+'-popover.html'; @@ -303,6 +245,27 @@ angular.module('emission.tripconfirm.multilabel', * This is the version that is called from the diary, where the trips are * geojson objects. We should unify this and populateManualInputs later. */ + + mls.populateInputsDummyInferences = function(trip, inputList) { + if (angular.isDefined(trip)) { + // console.log("Expectation: "+JSON.stringify(trip.expectation)); + // console.log("Inferred labels from server: "+JSON.stringify(trip.inferred_labels)); + trip.userInput = {}; + ConfirmHelper.INPUTS.forEach(function(item, index) { + mls.populateInputFromTimeline(trip, trip.nextTrip, item, + inputList[item]); + }); + // add additional data structures to make the trip gj similar to a trip object + // so that the rest of the load/save code works + trip.start_ts = trip.data.properties.start_ts; + trip.end_ts = trip.data.properties.end_ts; + trip.inferred_labels = []; + trip.finalInference = {}; + } else { + console.log("Trip information not yet bound, skipping fill"); + } + } + mls.populateInputFromTimeline = function (trip, nextTripgj, inputType, inputList) { console.log("While populating inputs, inputParams", mls.inputParams); var userInput = DiaryHelper.getUserInputForTrip(trip, nextTripgj, inputList); From 354dcd8672df1e3b753279236a24cf8378eb47cb Mon Sep 17 00:00:00 2001 From: Shankari Date: Mon, 4 Oct 2021 14:15:32 -0700 Subject: [PATCH 018/175] First round of unification - remove the duplicate implementations of the code that populates entries - call `populateInputsAndInferences` directly - fill in the fields needed for it to work ahead of time Testing done: - Loaded diary, no errors - Loaded label, no errors --- www/js/diary/list.js | 8 ++++++- www/js/tripconfirm/multi-label-ui.js | 34 ---------------------------- 2 files changed, 7 insertions(+), 35 deletions(-) diff --git a/www/js/diary/list.js b/www/js/diary/list.js index 38f7ae90d..d83abbee9 100644 --- a/www/js/diary/list.js +++ b/www/js/diary/list.js @@ -216,7 +216,13 @@ angular.module('emission.main.diary.list',['ui-leaflet', // Add "next" pointers to make it easier to use trip linkages for display $scope.data.currDayTripWrappers.forEach(function(tripgj, tripIndex, array) { tripgj.nextTripgj = array[tripIndex+1]; - $scope.labelPopulateFactory.populateInputsDummyInferences(tripgj, $scope.data.unifiedConfirmsResults); + + // add additional data structures to make the trip gj similar to a + // trip object so that the unified populate code works + tripgj.start_ts = tripgj.data.properties.start_ts; + tripgj.end_ts = tripgj.data.properties.end_ts; + tripgj.inferred_labels = []; + $scope.labelPopulateFactory.populateInputsAndInferences(tripgj, $scope.data.unifiedConfirmsResults); $scope.populateBasicClasses(tripgj); $scope.populateCommonInfo(tripgj); }); diff --git a/www/js/tripconfirm/multi-label-ui.js b/www/js/tripconfirm/multi-label-ui.js index 54a167f90..a9afc7dad 100644 --- a/www/js/tripconfirm/multi-label-ui.js +++ b/www/js/tripconfirm/multi-label-ui.js @@ -242,42 +242,8 @@ angular.module('emission.tripconfirm.multilabel', /** * Embed 'inputType' to the trip. - * This is the version that is called from the diary, where the trips are - * geojson objects. We should unify this and populateManualInputs later. */ - mls.populateInputsDummyInferences = function(trip, inputList) { - if (angular.isDefined(trip)) { - // console.log("Expectation: "+JSON.stringify(trip.expectation)); - // console.log("Inferred labels from server: "+JSON.stringify(trip.inferred_labels)); - trip.userInput = {}; - ConfirmHelper.INPUTS.forEach(function(item, index) { - mls.populateInputFromTimeline(trip, trip.nextTrip, item, - inputList[item]); - }); - // add additional data structures to make the trip gj similar to a trip object - // so that the rest of the load/save code works - trip.start_ts = trip.data.properties.start_ts; - trip.end_ts = trip.data.properties.end_ts; - trip.inferred_labels = []; - trip.finalInference = {}; - } else { - console.log("Trip information not yet bound, skipping fill"); - } - } - - mls.populateInputFromTimeline = function (trip, nextTripgj, inputType, inputList) { - console.log("While populating inputs, inputParams", mls.inputParams); - var userInput = DiaryHelper.getUserInputForTrip(trip, nextTripgj, inputList); - if (angular.isDefined(userInput)) { - // userInput is an object with data + metadata - // the label is the "value" from the options - mls.populateInput(trip.userInput, inputType, userInput.data.label); - } - // Logger.log("Set "+ inputType + " " + JSON.stringify(userInputEntry) + " for trip id " + JSON.stringify(trip.data.id)); - mls.editingTrip = angular.undefined; - } - mls.populateInputsAndInferences = function(trip, manualResultMap) { if (angular.isDefined(trip)) { // console.log("Expectation: "+JSON.stringify(trip.expectation)); From 3ec573446b2e56f865750d3da03744c2aafed158 Mon Sep 17 00:00:00 2001 From: Shankari Date: Mon, 4 Oct 2021 14:43:43 -0700 Subject: [PATCH 019/175] Simplify the invocation of `getUserInputForTrip` Since `getUserInputForTrip` is now called only from `populateManualInput` we can adapt it to take the trip inputs directly, and we don't have to massage the input to meet expecations The one minor ordering change to accomplish this was to compute the basic classes before matching the inputs so that we can use the `isDraft` variable directly. We don't (currently) show draft trips on the label screen, so it will be undefined there. And undefined != true, so it will only apply for diary trips. --- www/js/diary/services.js | 58 ++++++++++++++-------------- www/js/tripconfirm/multi-label-ui.js | 13 +++---- www/templates/diary/list.html | 3 +- 3 files changed, 35 insertions(+), 39 deletions(-) diff --git a/www/js/diary/services.js b/www/js/diary/services.js index 2ad24e8c2..94bdfb066 100644 --- a/www/js/diary/services.js +++ b/www/js/diary/services.js @@ -405,22 +405,22 @@ angular.module('emission.main.diary.services', ['emission.plugin.logger', " " + ui.data.label + " logged at "+ ui.metadata.write_ts; } - dh.getUserInputForTrip = function(tripgj, nextTripgj, userInputList) { + dh.getUserInputForTrip = function(trip, nextTrip, userInputList) { if (userInputList.length < 20) { console.log("Input list = "+userInputList.map(printUserInput)); } - var tripProp = tripgj.data.properties; - var isDraft = dh.isDraft(tripgj); + // undefined != true, so this covers the label view case as well + var isDraft = trip.isDraft == true; var potentialCandidates = userInputList.filter(function(userInput) { /* console.log("startDelta "+userInput.data.label+ "= user("+fmtTs(userInput.data.start_ts, userInput.metadata.time_zone)+ ") - trip("+fmtTs(userInput.data.start_ts, userInput.metadata.time_zone)+") = "+ - (userInput.data.start_ts - tripProp.start_ts)+" should be positive"); + (userInput.data.start_ts - trip.start_ts)+" should be positive"); console.log("endDelta = "+userInput.data.label+ "user("+fmtTs(userInput.data.end_ts, userInput.metadata.time_zone)+ - ") - trip("+fmtTs(tripProp.end_ts, userInput.metadata.time_zone)+") = "+ - (userInput.data.end_ts - tripProp.end_ts)+" should be negative"); + ") - trip("+fmtTs(trip.end_ts, userInput.metadata.time_zone)+") = "+ + (userInput.data.end_ts - trip.end_ts)+" should be negative"); */ // logic described in // https://github.com/e-mission/e-mission-docs/issues/423 @@ -428,19 +428,19 @@ angular.module('emission.main.diary.services', ['emission.plugin.logger', if (userInputList.length < 20) { var logStr = "Draft trip: comparing user = "+fmtTs(userInput.data.start_ts, userInput.metadata.time_zone) +" -> "+fmtTs(userInput.data.end_ts, userInput.metadata.time_zone) - +" trip = "+fmtTs(tripProp.start_ts, userInput.metadata.time_zone) - +" -> "+fmtTs(tripProp.end_ts, userInput.metadata.time_zone) - +" checks are ("+(userInput.data.start_ts >= tripProp.start_ts) - +" && "+(userInput.data.start_ts <= tripProp.end_ts) - +" || "+(-(userInput.data.start_ts - tripProp.start_ts) <= 15 * 60) - +") && "+(userInput.data.end_ts <= tripProp.end_ts); + +" trip = "+fmtTs(trip.start_ts, userInput.metadata.time_zone) + +" -> "+fmtTs(trip.end_ts, userInput.metadata.time_zone) + +" checks are ("+(userInput.data.start_ts >= trip.start_ts) + +" && "+(userInput.data.start_ts <= trip.end_ts) + +" || "+(-(userInput.data.start_ts - trip.start_ts) <= 15 * 60) + +") && "+(userInput.data.end_ts <= trip.end_ts); console.log(logStr); // Logger.log(logStr); } - return (userInput.data.start_ts >= tripProp.start_ts - && userInput.data.start_ts <= tripProp.end_ts - || -(userInput.data.start_ts - tripProp.start_ts) <= 15 * 60) - && userInput.data.end_ts <= tripProp.end_ts; + return (userInput.data.start_ts >= trip.start_ts + && userInput.data.start_ts <= trip.end_ts + || -(userInput.data.start_ts - trip.start_ts) <= 15 * 60) + && userInput.data.end_ts <= trip.end_ts; } else { // we know that the trip is cleaned so we can use the fmt_time // but the confirm objects are not necessarily filled out @@ -448,19 +448,19 @@ angular.module('emission.main.diary.services', ['emission.plugin.logger', var logStr = "Cleaned trip: comparing user = " +fmtTs(userInput.data.start_ts, userInput.metadata.time_zone) +" -> "+fmtTs(userInput.data.end_ts, userInput.metadata.time_zone) - +" trip = "+tripProp.start_fmt_time - +" -> "+tripProp.end_fmt_time - +" start checks are "+(userInput.data.start_ts >= tripProp.start_ts) - +" && "+(userInput.data.start_ts <= tripProp.end_ts) - +" end checks are "+(userInput.data.end_ts <= tripProp.end_ts) - +" || "+((userInput.data.end_ts - tripProp.end_ts) <= 15 * 60)+")"; + +" trip = "+trip.start_fmt_time + +" -> "+trip.end_fmt_time + +" start checks are "+(userInput.data.start_ts >= trip.start_ts) + +" && "+(userInput.data.start_ts <= trip.end_ts) + +" end checks are "+(userInput.data.end_ts <= trip.end_ts) + +" || "+((userInput.data.end_ts - trip.end_ts) <= 15 * 60)+")"; Logger.log(logStr); } // https://github.com/e-mission/e-mission-docs/issues/476#issuecomment-747222181 - const startChecks = userInput.data.start_ts >= tripProp.start_ts && - userInput.data.start_ts <= tripProp.end_ts; - var endChecks = (userInput.data.end_ts <= tripProp.end_ts || - (userInput.data.end_ts - tripProp.end_ts) <= 15 * 60); + const startChecks = userInput.data.start_ts >= trip.start_ts && + userInput.data.start_ts <= trip.end_ts; + var endChecks = (userInput.data.end_ts <= trip.end_ts || + (userInput.data.end_ts - trip.end_ts) <= 15 * 60); if (startChecks && !endChecks) { if (angular.isDefined(nextTripgj)) { endChecks = userInput.data.end_ts <= nextTripgj.data.properties.start_ts; @@ -474,10 +474,10 @@ angular.module('emission.main.diary.services', ['emission.plugin.logger', if (endChecks) { // If we have flipped the values, check to see that there // is sufficient overlap - const overlapDuration = Math.min(userInput.data.end_ts, tripProp.end_ts) - Math.max(userInput.data.start_ts, tripProp.start_ts) + const overlapDuration = Math.min(userInput.data.end_ts, trip.end_ts) - Math.max(userInput.data.start_ts, trip.start_ts) Logger.log("Flipped endCheck, overlap("+overlapDuration+ - ")/trip("+tripProp.duration+") = "+ (overlapDuration / tripProp.duration)); - endChecks = (overlapDuration/tripProp.duration) > 0.5; + ")/trip("+trip.duration+") = "+ (overlapDuration / trip.duration)); + endChecks = (overlapDuration/trip.duration) > 0.5; } } return startChecks && endChecks; diff --git a/www/js/tripconfirm/multi-label-ui.js b/www/js/tripconfirm/multi-label-ui.js index a9afc7dad..a88a43aba 100644 --- a/www/js/tripconfirm/multi-label-ui.js +++ b/www/js/tripconfirm/multi-label-ui.js @@ -266,19 +266,16 @@ angular.module('emission.tripconfirm.multilabel', * This is the version that is called from the list, which focuses only on * manual inputs. It also sets some additional values */ - mls.populateManualInputs = function (tripgj, nextTripgj, inputType, inputList) { + mls.populateManualInputs = function (trip, nextTrip, inputType, inputList) { // Check unprocessed labels first since they are more recent - // Massage the input to meet getUserInputForTrip expectations - const unprocessedLabelEntry = DiaryHelper.getUserInputForTrip( - {data: {properties: tripgj, features: [{}, {}, {}]}}, - {data: {properties: nextTripgj, features: [{}, {}, {}]}}, + const unprocessedLabelEntry = DiaryHelper.getUserInputForTrip(trip, nextTrip, inputList); var userInputLabel = unprocessedLabelEntry? unprocessedLabelEntry.data.label : undefined; if (!angular.isDefined(userInputLabel)) { - userInputLabel = tripgj.user_input[mls.inputType2retKey(inputType)]; + userInputLabel = trip.user_input[mls.inputType2retKey(inputType)]; } - mls.populateInput(tripgj.userInput, inputType, userInputLabel); - // Logger.log("Set "+ inputType + " " + JSON.stringify(userInputEntry) + " for trip starting at " + JSON.stringify(tripgj.start_fmt_time)); + mls.populateInput(trip.userInput, inputType, userInputLabel); + // Logger.log("Set "+ inputType + " " + JSON.stringify(userInputEntry) + " for trip starting at " + JSON.stringify(trip.start_fmt_time)); mls.editingTrip = angular.undefined; } diff --git a/www/templates/diary/list.html b/www/templates/diary/list.html index 22cb2ff61..3d685797b 100644 --- a/www/templates/diary/list.html +++ b/www/templates/diary/list.html @@ -92,8 +92,7 @@
- +
From 8a6d4b536960359197c5528e5fe8d4c9684d4a69 Mon Sep 17 00:00:00 2001 From: Shankari Date: Mon, 4 Oct 2021 15:52:35 -0700 Subject: [PATCH 020/175] Simplify and unify of the diary and label screens - Remove the unused dependency on `$q` (we use built-in promises instead) - Remove the page reload on background sync which was commented out a long time ago; we may also be removing/refactoring the background sync anyway - Remove `explainDraft`, `makeCurrent` from the label screen since we don't show draft trips there - Remove `prevDay`, `nextDay` from the label screen since we don't use day-based navigation - Remove the current trip code from the label screen since we don't have a way to launch it - Remove the code around groups which seems to have been added in (https://github.com/e-mission/e-mission-phone/commit/1e9572005889e657da915419a7a745de1f80dc49), has no documentation, uses `good1`, `good2` and `good3` as the groups - Add client stats to the diary code, similar to the label view - Remove unused `getTimeSplit` from both screens - Remove the code to refresh the maps in the diary view since we have removed that button - Remove unused `isNotEmpty` - Ensure that we don't consider the position to refresh since we don't pull to refresh any more --- www/js/diary/infinite_scroll_list.js | 118 +-------------------------- www/js/diary/list.js | 84 ++++++++----------- www/js/stats/clientstats.js | 2 + 3 files changed, 36 insertions(+), 168 deletions(-) diff --git a/www/js/diary/infinite_scroll_list.js b/www/js/diary/infinite_scroll_list.js index e64d942bf..394510060 100644 --- a/www/js/diary/infinite_scroll_list.js +++ b/www/js/diary/infinite_scroll_list.js @@ -11,8 +11,7 @@ angular.module('emission.main.diary.infscrolllist',['ui-leaflet', 'ionic-datepicker', 'emission.main.common.services', - 'emission.incident.posttrip.manual', - 'emission.tripconfirm.services', + 'emission.tripconfirm.multilabel', 'emission.tripconfirm.verifycheck', 'emission.services', 'ng-walkthrough', 'nzTour', 'emission.plugin.kvstore', @@ -28,7 +27,7 @@ angular.module('emission.main.diary.infscrolllist',['ui-leaflet', $timeout, ionicDatePicker, leafletData, Timeline, CommonGraph, DiaryHelper, - Config, PostTripManualMarker, nzTour, KVStore, Logger, UnifiedDataLoader, $ionicPopover, $ionicModal, $translate, $q) { + Config, PostTripManualMarker, nzTour, KVStore, Logger, UnifiedDataLoader, $ionicPopover, $ionicModal, $translate) { // TODO: load only a subset of entries instead of everything @@ -352,55 +351,10 @@ angular.module('emission.main.diary.infscrolllist',['ui-leaflet', tripgj.common.displayEarlierLater = $scope.parseEarlierOrLater(tripgj.common.earlierOrLater); } - $scope.explainDraft = function($event) { - $event.stopPropagation(); - $ionicPopup.alert({ - template: $translate.instant('list-explainDraft-alert') - }); - // don't want to go to the detail screen - } - - /* - * Disabling the reload of the page on background sync because it doesn't - * work correctly. on iOS, plugins are not loaded if backgroundFetch or - * remote push are invoked, since they don't initialize the app. On - * android, it looks like the thread ends before the maps are fully loaded, - * so we have half displayed, frozen maps. We should really check the - * status, reload here if active and reload everything on resume. - * For now, we just add a refresh button to avoid maintaining state. - window.broadcaster.addEventListener( "edu.berkeley.eecs.emission.sync.NEW_DATA", function( e ) { - window.Logger.log(window.Logger.LEVEL_INFO, - "new data received! reload data for the current day"+$scope.data.currDay); - $window.location.reload(); - // readAndUpdateForDay($scope.data.currDay); - }); - */ - $scope.refresh = function() { $scope.setupInfScroll(); }; - /* For UI control */ - $scope.groups = []; - for (var i=0; i<10; i++) { - $scope.groups[i] = { - name: i, - items: ["good1", "good2", "good3"] - }; - for (var j=0; j<3; j++) { - $scope.groups[i].items.push(i + '-' + j); - } - } - $scope.toggleGroup = function(group) { - if ($scope.isGroupShown(group)) { - $scope.shownGroup = null; - } else { - $scope.shownGroup = group; - } - }; - $scope.isGroupShown = function(group) { - return $scope.shownGroup === group; - }; $scope.getEarlierOrLater = DiaryHelper.getEarlierOrLater; $scope.getLongerOrShorter = DiaryHelper.getLongerOrShorter; $scope.getHumanReadable = DiaryHelper.getHumanReadable; @@ -420,22 +374,8 @@ angular.module('emission.main.diary.infscrolllist',['ui-leaflet', // $scope.expandEarlierOrLater = DiaryHelper.expandEarlierOrLater; // $scope.increaseRestElementsTranslate3d = DiaryHelper.increaseRestElementsTranslate3d; - $scope.makeCurrent = function() { - $ionicPopup.alert({ - template: "Coming soon, after Shankari's quals in early March!" - }); - } - $scope.parseEarlierOrLater = DiaryHelper.parseEarlierOrLater; - $scope.getTimeSplit = function(tripList) { - var retVal = {}; - var tripTimes = tripList.map(function(dt) { - return dt.data.properties.duration; - }); - - }; - // Tour steps var tour = { config: { @@ -512,10 +452,8 @@ angular.module('emission.main.diary.infscrolllist',['ui-leaflet', var startWalkthrough = function () { nzTour.start(tour).then(function(result) { - // $ionicScrollDelegate.scrollBottom(); Logger.log("list walkthrough start completed, no error"); }).catch(function(err) { - // $ionicScrollDelegate.scrollBottom(); Logger.displayError("list walkthrough start errored", err); }); }; @@ -566,58 +504,6 @@ angular.module('emission.main.diary.infscrolllist',['ui-leaflet', } }) - $scope.prevDay = function() { - console.log("Called prevDay when currDay = "+Timeline.data.currDay.format('YYYY-MM-DD')); - var prevDay = moment(Timeline.data.currDay).subtract(1, 'days'); - console.log("prevDay = "+prevDay.format('YYYY-MM-DD')); - readAndUpdateForDay(prevDay); - }; - - $scope.nextDay = function() { - console.log("Called nextDay when currDay = "+Timeline.data.currDay.format('YYYY-MM-DD')); - var nextDay = moment(Timeline.data.currDay).add(1, 'days'); - console.log("nextDay = "+nextDay); - readAndUpdateForDay(nextDay); - }; - - $scope.toDetail = function (param) { - $state.go('root.main.diary-detail', { - tripId: param - }); - }; - - $scope.showModes = DiaryHelper.showModes; - - $scope.redirect = function(){ - $state.go("root.main.current"); - }; - - var in_trip; - $scope.checkTripState = function() { - window.cordova.plugins.BEMDataCollection.getState().then(function(result) { - Logger.log("Current trip state" + JSON.stringify(result)); - if(JSON.stringify(result) == "\"STATE_ONGOING_TRIP\"" || - JSON.stringify(result) == "\"local.state.ongoing_trip\"") { - in_trip = true; - } else { - in_trip = false; - } - }); - }; - - // storing boolean to in_trip and return it in inTrip function - // work because ng-show is watching the inTrip function. - // Returning a promise to ng-show did not work. - // Changing in_trip = bool value; in checkTripState function - // to return bool value and using checkTripState function in ng-show - // did not work. - $scope.inTrip = function() { - $ionicPlatform.ready().then(function() { - $scope.checkTripState(); - return in_trip; - }); - }; - $ionicPlatform.ready().then(function() { $scope.setupInfScroll(); $scope.isAndroid = $window.device.platform.toLowerCase() === "android"; diff --git a/www/js/diary/list.js b/www/js/diary/list.js index d83abbee9..a7f6f0055 100644 --- a/www/js/diary/list.js +++ b/www/js/diary/list.js @@ -11,31 +11,28 @@ angular.module('emission.main.diary.list',['ui-leaflet', 'ionic-datepicker', 'emission.main.common.services', - 'emission.incident.posttrip.manual', 'emission.tripconfirm.multilabel', 'emission.tripconfirm.verifycheck', 'emission.services', 'ng-walkthrough', 'nzTour', 'emission.plugin.kvstore', - 'emission.plugin.logger' + 'emission.stats.clientstats', + 'emission.plugin.logger' ]) .controller("DiaryListCtrl", function($window, $scope, $rootScope, $injector, $ionicPlatform, $state, - $ionicScrollDelegate, $ionicPopup, + $ionicScrollDelegate, $ionicPopup, ClientStats, $ionicLoading, $ionicActionSheet, ionicDatePicker, leafletData, Timeline, CommonGraph, DiaryHelper, Config, PostTripManualMarker, nzTour, KVStore, Logger, UnifiedDataLoader, $ionicPopover, $translate) { console.log("controller DiaryListCtrl called"); + ClientStats.addReading(ClientStats.getStatKeys().LABEL_TAB_SWITCH, + {"source": null, "dest": $scope.data? $scope.data.currDay : undefined}); // Add option $scope.labelPopulateFactory = $injector.get("MultiLabelService"); - $scope.$on('leafletDirectiveMap.resize', function(event, data) { - console.log("diary/list received resize event, invalidating map size"); - data.leafletObject.invalidateSize(); - }); - var readAndUpdateForDay = function(day) { // This just launches the update. The update can complete in the background // based on the time when the database finishes reading. @@ -185,14 +182,6 @@ angular.module('emission.main.diary.list',['ui-leaflet', tripgj.common.displayEarlierLater = $scope.parseEarlierOrLater(tripgj.common.earlierOrLater); } - var isNotEmpty = function (obj) { - for (var prop in obj) { - if (obj.hasOwnProperty(prop)) - return true; - } - return false; - }; - $scope.explainDraft = function($event) { $event.stopPropagation(); $ionicPopup.alert({ @@ -217,13 +206,16 @@ angular.module('emission.main.diary.list',['ui-leaflet', $scope.data.currDayTripWrappers.forEach(function(tripgj, tripIndex, array) { tripgj.nextTripgj = array[tripIndex+1]; + // First populate basic classes so that we can use `isDraft` during + // the matching code + $scope.populateBasicClasses(tripgj); + // add additional data structures to make the trip gj similar to a // trip object so that the unified populate code works tripgj.start_ts = tripgj.data.properties.start_ts; tripgj.end_ts = tripgj.data.properties.end_ts; tripgj.inferred_labels = []; $scope.labelPopulateFactory.populateInputsAndInferences(tripgj, $scope.data.unifiedConfirmsResults); - $scope.populateBasicClasses(tripgj); $scope.populateCommonInfo(tripgj); }); if ($rootScope.displayingIncident) { @@ -299,33 +291,10 @@ angular.module('emission.main.diary.list',['ui-leaflet', */ $scope.refresh = function() { - if ($ionicScrollDelegate.getScrollPosition().top < 20) { readAndUpdateForDay(Timeline.data.currDay); $scope.$broadcast('invalidateSize'); - } }; - /* For UI control */ - $scope.groups = []; - for (var i=0; i<10; i++) { - $scope.groups[i] = { - name: i, - items: ["good1", "good2", "good3"] - }; - for (var j=0; j<3; j++) { - $scope.groups[i].items.push(i + '-' + j); - } - } - $scope.toggleGroup = function(group) { - if ($scope.isGroupShown(group)) { - $scope.shownGroup = null; - } else { - $scope.shownGroup = group; - } - }; - $scope.isGroupShown = function(group) { - return $scope.shownGroup === group; - }; $scope.getEarlierOrLater = DiaryHelper.getEarlierOrLater; $scope.getLongerOrShorter = DiaryHelper.getLongerOrShorter; $scope.getHumanReadable = DiaryHelper.getHumanReadable; @@ -353,14 +322,6 @@ angular.module('emission.main.diary.list',['ui-leaflet', $scope.parseEarlierOrLater = DiaryHelper.parseEarlierOrLater; - $scope.getTimeSplit = function(tripList) { - var retVal = {}; - var tripTimes = tripList.map(function(dt) { - return dt.data.properties.duration; - }); - - }; - // Tour steps var tour = { config: { @@ -395,10 +356,6 @@ angular.module('emission.main.diary.list',['ui-leaflet', }); }; - $scope.refreshTiles = function() { - $scope.$broadcast('invalidateSize'); - }; - /* * Checks if it is the first time the user has loaded the diary tab. If it is then * show a walkthrough and store the info that the user has seen the tutorial. @@ -476,6 +433,7 @@ angular.module('emission.main.diary.list',['ui-leaflet', readAndUpdateForDay(moment().startOf('day')); $scope.$on('$ionicView.enter', function(ev) { + $scope.startTime = moment().utc() // Workaround from // https://github.com/driftyco/ionic/issues/3433#issuecomment-195775629 if(ev.targetScope !== $scope) @@ -483,7 +441,29 @@ angular.module('emission.main.diary.list',['ui-leaflet', checkDiaryTutorialDone(); }); + $scope.$on('$ionicView.leave',function() { + var timeOnPage = moment().utc() - $scope.startTime; + ClientStats.addReading(ClientStats.getStatKeys().DIARY_TIME, timeOnPage); + }); + + $ionicPlatform.on("pause", function() { + if ($state.$current == "root.main.diary.list") { + var timeOnPage = moment().utc() - $scope.startTime; + ClientStats.addReading(ClientStats.getStatKeys().DIARY_TIME, timeOnPage); + } + }) + + $ionicPlatform.on("resume", function() { + if ($state.$current == "root.main.diary.list") { + $scope.startTime = moment().utc() + } + }) + + $scope.$on('$ionicView.afterEnter', function() { + ClientStats.addEvent(ClientStats.getStatKeys().CHECKED_DIARY).then(function() { + console.log("Added "+ClientStats.getStatKeys().CHECKED_DIARY+" event"); + }); if($rootScope.barDetail){ readAndUpdateForDay($rootScope.barDetailDate); $rootScope.barDetail = false; diff --git a/www/js/stats/clientstats.js b/www/js/stats/clientstats.js index c94dc07f4..1c1f97276 100644 --- a/www/js/stats/clientstats.js +++ b/www/js/stats/clientstats.js @@ -13,6 +13,8 @@ angular.module('emission.stats.clientstats', []) return { STATE_CHANGED: "state_changed", BUTTON_FORCE_SYNC: "button_sync_forced", + CHECKED_DIARY: "checked_diary", + DIARY_TIME: "diary_time", CHECKED_INF_SCROLL: "checked_inf_scroll", INF_SCROLL_TIME: "inf_scroll_time", VERIFY_TRIP: "verify_trip", From a96194d5d8ac30f501e41cd0bf488093a2e0b4eb Mon Sep 17 00:00:00 2001 From: Shankari Date: Mon, 4 Oct 2021 16:34:22 -0700 Subject: [PATCH 021/175] Second round of unification/cleanup Remove all the references from the diary helper to `$scope` variables. These were added back when we displayed common trips (https://github.com/e-mission/e-mission-phone/commit/c393e3d96e1186d165cc3cddbbef4588dfbf1609) in order to avoid duplicating the common trip information between the list view and the common trips code. We then used them directly in the UI to format data for display. However, as part of https://github.com/e-mission/e-mission-phone/commit/30561b94d8691e37fc3e50b8488f5da82f6dd815 we changed the template to populate values from trip variables instead of `$scope` functions. So this reassignment is no longer required. Let's remove them and replace them with direct calls to the diary helper. --- www/js/diary/infinite_scroll_list.js | 29 ++-------------------------- www/js/diary/list.js | 28 +++------------------------ www/js/diary/services.js | 5 +++++ 3 files changed, 10 insertions(+), 52 deletions(-) diff --git a/www/js/diary/infinite_scroll_list.js b/www/js/diary/infinite_scroll_list.js index 394510060..2cfb4346f 100644 --- a/www/js/diary/infinite_scroll_list.js +++ b/www/js/diary/infinite_scroll_list.js @@ -304,16 +304,12 @@ angular.module('emission.main.diary.infscrolllist',['ui-leaflet', return ($scope.differentCommon(tripgj))? "stop-time-tag-lower" : "stop-time-tag"; } - $scope.getFormattedDistanceInMiles = function(input) { - return (0.621371 * $scope.getFormattedDistance(input)).toFixed(1); - } - $scope.populateBasicClasses = function(tripgj) { tripgj.display_start_time = DiaryHelper.getLocalTimeString(tripgj.start_local_dt); tripgj.display_end_time = DiaryHelper.getLocalTimeString(tripgj.end_local_dt); - tripgj.display_distance = $scope.getFormattedDistanceInMiles(tripgj.distance); + tripgj.display_distance = DiaryHelper.getFormattedDistance(tripgj.distance); tripgj.display_date = moment(tripgj.start_ts * 1000).format('ddd DD MMM YY'); - tripgj.display_time = $scope.getFormattedTimeRange(tripgj.start_ts, + tripgj.display_time = DiaryHelper.getFormattedTimeRange(tripgj.start_ts, tripgj.end_ts); tripgj.background = "bg-light"; tripgj.listCardClass = $scope.listCardClass(tripgj); @@ -355,27 +351,6 @@ angular.module('emission.main.diary.infscrolllist',['ui-leaflet', $scope.setupInfScroll(); }; - $scope.getEarlierOrLater = DiaryHelper.getEarlierOrLater; - $scope.getLongerOrShorter = DiaryHelper.getLongerOrShorter; - $scope.getHumanReadable = DiaryHelper.getHumanReadable; - $scope.getKmph = DiaryHelper.getKmph; - $scope.getPercentages = DiaryHelper.getPercentages; - $scope.getFormattedDistance = DiaryHelper.getFormattedDistance; - $scope.getSectionDetails = DiaryHelper.getSectionDetails; - $scope.getFormattedTime = DiaryHelper.getFormattedTime; - $scope.getFormattedTimeRange = DiaryHelper.getFormattedTimeRange; - $scope.getFormattedDuration = DiaryHelper.getFormattedDuration; - $scope.getTripDetails = DiaryHelper.getTripDetails; - $scope.starColor = DiaryHelper.starColor; - $scope.arrowColor = DiaryHelper.arrowColor; - $scope.getArrowClass = DiaryHelper.getArrowClass; - $scope.isCommon = DiaryHelper.isCommon; - $scope.isDraft = DiaryHelper.isDraft; - // $scope.expandEarlierOrLater = DiaryHelper.expandEarlierOrLater; - // $scope.increaseRestElementsTranslate3d = DiaryHelper.increaseRestElementsTranslate3d; - - $scope.parseEarlierOrLater = DiaryHelper.parseEarlierOrLater; - // Tour steps var tour = { config: { diff --git a/www/js/diary/list.js b/www/js/diary/list.js index a7f6f0055..e43e5462b 100644 --- a/www/js/diary/list.js +++ b/www/js/diary/list.js @@ -159,10 +159,10 @@ angular.module('emission.main.diary.list',['ui-leaflet', $scope.populateBasicClasses = function(tripgj) { tripgj.display_start_time = DiaryHelper.getLocalTimeString(tripgj.data.properties.start_local_dt); tripgj.display_end_time = DiaryHelper.getLocalTimeString(tripgj.data.properties.end_local_dt); - tripgj.display_distance = $scope.getFormattedDistance(tripgj.data.properties.distance); - tripgj.display_time = $scope.getFormattedTimeRange(tripgj.data.properties.start_ts, + tripgj.display_distance = DiaryHelper.getFormattedDistance(tripgj.data.properties.distance); + tripgj.display_time = DiaryHelper.getFormattedTimeRange(tripgj.data.properties.start_ts, tripgj.data.properties.end_ts); - tripgj.isDraft = $scope.isDraft(tripgj); + tripgj.isDraft = DiaryHelper.isDraft(tripgj); tripgj.background = DiaryHelper.getTripBackground(tripgj); tripgj.listCardClass = $scope.listCardClass(tripgj); tripgj.percentages = $scope.getPercentages(tripgj) @@ -292,36 +292,14 @@ angular.module('emission.main.diary.list',['ui-leaflet', $scope.refresh = function() { readAndUpdateForDay(Timeline.data.currDay); - $scope.$broadcast('invalidateSize'); }; - $scope.getEarlierOrLater = DiaryHelper.getEarlierOrLater; - $scope.getLongerOrShorter = DiaryHelper.getLongerOrShorter; - $scope.getHumanReadable = DiaryHelper.getHumanReadable; - $scope.getKmph = DiaryHelper.getKmph; - $scope.getPercentages = DiaryHelper.getPercentages; - $scope.getFormattedDistance = DiaryHelper.getFormattedDistance; - $scope.getSectionDetails = DiaryHelper.getSectionDetails; - $scope.getFormattedTime = DiaryHelper.getFormattedTime; - $scope.getFormattedTimeRange = DiaryHelper.getFormattedTimeRange; - $scope.getFormattedDuration = DiaryHelper.getFormattedDuration; - $scope.getTripDetails = DiaryHelper.getTripDetails; - $scope.starColor = DiaryHelper.starColor; - $scope.arrowColor = DiaryHelper.arrowColor; - $scope.getArrowClass = DiaryHelper.getArrowClass; - $scope.isCommon = DiaryHelper.isCommon; - $scope.isDraft = DiaryHelper.isDraft; - // $scope.expandEarlierOrLater = DiaryHelper.expandEarlierOrLater; - // $scope.increaseRestElementsTranslate3d = DiaryHelper.increaseRestElementsTranslate3d; - $scope.makeCurrent = function() { $ionicPopup.alert({ template: "Coming soon, after Shankari's quals in early March!" }); } - $scope.parseEarlierOrLater = DiaryHelper.parseEarlierOrLater; - // Tour steps var tour = { config: { diff --git a/www/js/diary/services.js b/www/js/diary/services.js index 94bdfb066..7ebd6f115 100644 --- a/www/js/diary/services.js +++ b/www/js/diary/services.js @@ -155,6 +155,11 @@ angular.module('emission.main.diary.services', ['emission.plugin.logger', return (dist_in_meters/1000).toFixed(3); } } + + dh.getFormattedDistanceInMiles = function(input) { + return (0.621371 * dh.getFormattedDistance(input)).toFixed(1); + } + dh.getSectionDetails = function(section) { var startMoment = moment(section.properties.start_ts * 1000); var endMoment = moment(section.properties.end_ts * 1000); From a3623e10f0fd4972d8c27ceb7dc50e980a716910 Mon Sep 17 00:00:00 2001 From: Attawit Kittikrairit Date: Tue, 28 Sep 2021 12:55:54 +0700 Subject: [PATCH 022/175] patch(SurveyLaunch): startSurveyPrefilled support auto close --- www/js/survey/launch.js | 46 +++++++++++++++++++++++++++++++++++------ 1 file changed, 40 insertions(+), 6 deletions(-) diff --git a/www/js/survey/launch.js b/www/js/survey/launch.js index 57e6d4a85..99447ed59 100644 --- a/www/js/survey/launch.js +++ b/www/js/survey/launch.js @@ -161,20 +161,52 @@ angular.module('emission.survey.launch', ['emission.services', startSurveyCommon(url, elementXPath, "js/survey/uuid_insert_xpath.js"); } - surveylaunch.startSurveyPrefilled = function (url, uuidSearchParam) { - CommHelper.getUser().then(function(userProfile) { + /** + * startSurveyPrefilled start the survey and prefill the UUID field. + * @param {string} url survey url + * @param {{ + * uuidSearchParam: string + * returnURLSearchParam: string + * returnURL: string + * autoCloseURL: string + * }} [opts] options + */ + surveylaunch.startSurveyPrefilled = function (url, opts = {}) { + opts = Object.assign({ + uuidSearchParam: 'uuid', + returnURLSearchParam: 'return_url', + returnURL: '', + autoCloseURL: undefined, + }, opts); + return CommHelper.getUser().then(function(userProfile) { // alert("finished loading script"); let uuid = userProfile.user_id['$uuid'] Logger.log("inserting user id into survey. userId = "+ uuid +" base url = "+url); - let urlObj = new URL(url); - urlObj.searchParams.append(uuidSearchParam, uuid); - let modifiedURL = urlObj.href; + const urlObj = new URL(url); + urlObj.searchParams.append(opts.returnURLSearchParam, encodeURIComponent(opts.returnURL)); + urlObj.searchParams.append(opts.uuidSearchParam, uuid); + const modifiedURL = urlObj.toString(); Logger.log("modified URL = "+modifiedURL); let iab = $window.cordova.InAppBrowser.open(modifiedURL, '_blank', surveylaunch.options); iab.addEventListener('loaderror', function(event) { Logger.displayError("Unable to launch survey", event); + return Promise.reject(); }); + if (opts.autoCloseURL) { + return new Promise((resolve, reject) => { + const autoClose = function(event) { + console.log("started loading, event = " + JSON.stringify(event)); + if (opts.autoCloseURL.includes(event.url)) { + iab.removeEventListener('loadstart', autoClose); + iab.close(); + return resolve(); + } + }; + iab.addEventListener('loadstart', autoClose); + }); + } + return Promise.resolve(); }); } @@ -193,7 +225,9 @@ angular.module('emission.survey.launch', ['emission.services', } else if (angular.isDefined(survey_spec.uuidXPath)) { surveylaunch.startSurveyWithXPath(survey_spec.url, survey_spec.uuidXPath); } else if (angular.isDefined(survey_spec.uuidSearchParam)) { - surveylaunch.startSurveyPrefilled(survey_spec.url, survey_spec.uuidSearchParam); + surveylaunch.startSurveyPrefilled(survey_spec.url, { + uuidSearchParam: survey_spec.uuidSearchParam + }); } else { $ionicPopup.alert("survey was not specified correctly. spec is "+JSON.stringify(survey_spec)); } From 2b02d7ddabd926350c641f20bde06d6faede23f5 Mon Sep 17 00:00:00 2001 From: Shankari Date: Mon, 4 Oct 2021 22:33:53 -0700 Subject: [PATCH 023/175] Invoke additional methods directly from the DiaryHelper In https://github.com/e-mission/e-mission-phone/pull/799/commits/a96194d5d8ac30f501e41cd0bf488093a2e0b4eb, we removed the references to `DiaryHelper` methods in `$scope`. In this follow-on, we change `populateCommonInfo` to invoke calls directly from the DiaryHelper instead of the `$scope`. Testing done: - Does not generate errors while populating the list view --- www/js/diary/infinite_scroll_list.js | 12 ++++++------ www/js/diary/list.js | 14 +++++++------- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/www/js/diary/infinite_scroll_list.js b/www/js/diary/infinite_scroll_list.js index 2cfb4346f..b1746350f 100644 --- a/www/js/diary/infinite_scroll_list.js +++ b/www/js/diary/infinite_scroll_list.js @@ -298,7 +298,7 @@ angular.module('emission.main.diary.infscrolllist',['ui-leaflet', $scope.listColRightClass = "col-50 list-col-right" $scope.differentCommon = function(tripgj) { - return ($scope.isCommon(tripgj.id))? ((DiaryHelper.getEarlierOrLater(tripgj.data.properties.start_ts, tripgj.data.id) == '')? false : true) : false; + return (DiaryHelper.isCommon(tripgj.id))? ((DiaryHelper.getEarlierOrLater(tripgj.data.properties.start_ts, tripgj.data.id) == '')? false : true) : false; } $scope.stopTimeTagClass = function(tripgj) { return ($scope.differentCommon(tripgj))? "stop-time-tag-lower" : "stop-time-tag"; @@ -337,14 +337,14 @@ angular.module('emission.main.diary.infscrolllist',['ui-leaflet', tripgj.common = {} DiaryHelper.fillCommonTripCount(tripgj); tripgj.common.different = $scope.differentCommon(tripgj); - tripgj.common.longerOrShorter = $scope.getLongerOrShorter(tripgj.data, tripgj.data.id); + tripgj.common.longerOrShorter = DiaryHelper.getLongerOrShorter(tripgj.data, tripgj.data.id); tripgj.common.listColLeftClass = $scope.listColLeftClass(tripgj.common.longerOrShorter[0]); tripgj.common.stopTimeTagClass = $scope.stopTimeTagClass(tripgj); - tripgj.common.arrowColor = $scope.arrowColor(tripgj.common.longerOrShorter[0]); - tripgj.common.arrowClass = $scope.getArrowClass(tripgj.common.longerOrShorter[0]); + tripgj.common.arrowColor = DiaryHelper.arrowColor(tripgj.common.longerOrShorter[0]); + tripgj.common.arrowClass = DiaryHelper.getArrowClass(tripgj.common.longerOrShorter[0]); - tripgj.common.earlierOrLater = $scope.getEarlierOrLater(tripgj.data.properties.start_ts, tripgj.data.id); - tripgj.common.displayEarlierLater = $scope.parseEarlierOrLater(tripgj.common.earlierOrLater); + tripgj.common.earlierOrLater = DiaryHelper.getEarlierOrLater(tripgj.data.properties.start_ts, tripgj.data.id); + tripgj.common.displayEarlierLater = DiaryHelper.parseEarlierOrLater(tripgj.common.earlierOrLater); } $scope.refresh = function() { diff --git a/www/js/diary/list.js b/www/js/diary/list.js index e43e5462b..7fd12cc28 100644 --- a/www/js/diary/list.js +++ b/www/js/diary/list.js @@ -106,7 +106,7 @@ angular.module('emission.main.diary.list',['ui-leaflet', $scope.listColRightClass = "col-50 list-col-right" $scope.differentCommon = function(tripgj) { - return ($scope.isCommon(tripgj.id))? ((DiaryHelper.getEarlierOrLater(tripgj.data.properties.start_ts, tripgj.data.id) == '')? false : true) : false; + return (DiaryHelper.isCommon(tripgj.id))? ((DiaryHelper.getEarlierOrLater(tripgj.data.properties.start_ts, tripgj.data.id) == '')? false : true) : false; } $scope.stopTimeTagClass = function(tripgj) { return ($scope.differentCommon(tripgj))? "stop-time-tag-lower" : "stop-time-tag"; @@ -165,21 +165,21 @@ angular.module('emission.main.diary.list',['ui-leaflet', tripgj.isDraft = DiaryHelper.isDraft(tripgj); tripgj.background = DiaryHelper.getTripBackground(tripgj); tripgj.listCardClass = $scope.listCardClass(tripgj); - tripgj.percentages = $scope.getPercentages(tripgj) + tripgj.percentages = DiaryHelper.getPercentages(tripgj) } $scope.populateCommonInfo = function(tripgj) { tripgj.common = {} DiaryHelper.fillCommonTripCount(tripgj); tripgj.common.different = $scope.differentCommon(tripgj); - tripgj.common.longerOrShorter = $scope.getLongerOrShorter(tripgj.data, tripgj.data.id); + tripgj.common.longerOrShorter = DiaryHelper.getLongerOrShorter(tripgj.data, tripgj.data.id); tripgj.common.listColLeftClass = $scope.listColLeftClass(tripgj.common.longerOrShorter[0]); tripgj.common.stopTimeTagClass = $scope.stopTimeTagClass(tripgj); - tripgj.common.arrowColor = $scope.arrowColor(tripgj.common.longerOrShorter[0]); - tripgj.common.arrowClass = $scope.getArrowClass(tripgj.common.longerOrShorter[0]); + tripgj.common.arrowColor = DiaryHelper.arrowColor(tripgj.common.longerOrShorter[0]); + tripgj.common.arrowClass = DiaryHelper.getArrowClass(tripgj.common.longerOrShorter[0]); - tripgj.common.earlierOrLater = $scope.getEarlierOrLater(tripgj.data.properties.start_ts, tripgj.data.id); - tripgj.common.displayEarlierLater = $scope.parseEarlierOrLater(tripgj.common.earlierOrLater); + tripgj.common.earlierOrLater = DiaryHelper.getEarlierOrLater(tripgj.data.properties.start_ts, tripgj.data.id); + tripgj.common.displayEarlierLater = DiaryHelper.parseEarlierOrLater(tripgj.common.earlierOrLater); } $scope.explainDraft = function($event) { From 9d677bfcbe4be295317c2da825fcfb8fa1f6e850 Mon Sep 17 00:00:00 2001 From: Shankari Date: Mon, 4 Oct 2021 22:40:52 -0700 Subject: [PATCH 024/175] Created a more principled directory structure for the surveys - survey/external: externally launched surveys - survey/multilabel: multiple labels - survey/enketo: (in the future) for eneketosurvey - survey/hexmap: (in the future) for itinerum surveys + Fixed all paths in index.html + Changed all the module names + Changed all module imports in the files that used them --- www/index.html | 14 +++++++------- www/js/controllers.js | 5 ++--- www/js/diary/infinite_scroll_list.js | 6 +++--- www/js/diary/list.js | 4 ++-- www/js/diary/services.js | 2 +- www/js/goals.js | 2 +- www/js/intro.js | 1 + www/js/main.js | 2 +- www/js/survey/{ => external}/launch.js | 2 +- www/js/survey/{ => external}/time_insert.js | 0 www/js/survey/{ => external}/uuid_insert_id.js | 0 www/js/survey/{ => external}/uuid_insert_xpath.js | 0 .../multilabel}/infinite_scroll_filters.js | 4 ++-- .../multilabel}/multi-label-ui.js | 4 ++-- .../multilabel}/one-click-button.js | 4 ++-- .../multilabel}/post-trip-map-display.js | 4 ++-- .../multilabel}/post-trip-prompt.js | 2 +- .../multilabel}/trip-confirm-services.js | 2 +- 18 files changed, 29 insertions(+), 29 deletions(-) rename www/js/survey/{ => external}/launch.js (99%) rename www/js/survey/{ => external}/time_insert.js (100%) rename www/js/survey/{ => external}/uuid_insert_id.js (100%) rename www/js/survey/{ => external}/uuid_insert_xpath.js (100%) rename www/js/{diary => survey/multilabel}/infinite_scroll_filters.js (94%) rename www/js/{tripconfirm => survey/multilabel}/multi-label-ui.js (99%) rename www/js/{tripconfirm => survey/multilabel}/one-click-button.js (91%) rename www/js/{tripconfirm => survey/multilabel}/post-trip-map-display.js (98%) rename www/js/{tripconfirm => survey/multilabel}/post-trip-prompt.js (99%) rename www/js/{tripconfirm => survey/multilabel}/trip-confirm-services.js (97%) diff --git a/www/index.html b/www/index.html index 2795caf8d..d24610d24 100644 --- a/www/index.html +++ b/www/index.html @@ -79,15 +79,15 @@ - - - - - + + + + + + - @@ -98,7 +98,7 @@ - + diff --git a/www/js/controllers.js b/www/js/controllers.js index 7105f8176..2889092cc 100644 --- a/www/js/controllers.js +++ b/www/js/controllers.js @@ -5,9 +5,8 @@ angular.module('emission.controllers', ['emission.splash.updatecheck', 'emission.splash.pushnotify', 'emission.splash.storedevicesettings', 'emission.splash.localnotify', - 'emission.survey.launch', 'emission.stats.clientstats', - 'emission.tripconfirm.posttrip.prompt']) + 'emission.survey.multilabel.posttrip.prompt']) .controller('RootCtrl', function($scope) {}) @@ -15,7 +14,7 @@ angular.module('emission.controllers', ['emission.splash.updatecheck', .controller('SplashCtrl', function($scope, $state, $interval, $rootScope, UpdateCheck, StartPrefs, PushNotify, StoreDeviceSettings, - LocalNotify, ClientStats, PostTripAutoPrompt, SurveyLaunch) { + LocalNotify, ClientStats, PostTripAutoPrompt) { console.log('SplashCtrl invoked'); // alert("attach debugger!"); // PushNotify.startupInit(); diff --git a/www/js/diary/infinite_scroll_list.js b/www/js/diary/infinite_scroll_list.js index b1746350f..5d8e7f8d7 100644 --- a/www/js/diary/infinite_scroll_list.js +++ b/www/js/diary/infinite_scroll_list.js @@ -11,11 +11,11 @@ angular.module('emission.main.diary.infscrolllist',['ui-leaflet', 'ionic-datepicker', 'emission.main.common.services', - 'emission.tripconfirm.multilabel', - 'emission.tripconfirm.verifycheck', + 'emission.survey.multilabel.buttons', + 'emission.survey.multilabel.verifycheck', 'emission.services', 'ng-walkthrough', 'nzTour', 'emission.plugin.kvstore', - 'emission.main.diary.infscrollfilters', + 'emission.survey.multilabel.infscrollfilters', 'emission.stats.clientstats', 'emission.plugin.logger']) diff --git a/www/js/diary/list.js b/www/js/diary/list.js index 7fd12cc28..3e4391c02 100644 --- a/www/js/diary/list.js +++ b/www/js/diary/list.js @@ -11,8 +11,8 @@ angular.module('emission.main.diary.list',['ui-leaflet', 'ionic-datepicker', 'emission.main.common.services', - 'emission.tripconfirm.multilabel', - 'emission.tripconfirm.verifycheck', + 'emission.survey.multilabel.buttons', + 'emission.survey.multilabel.verifycheck', 'emission.services', 'ng-walkthrough', 'nzTour', 'emission.plugin.kvstore', 'emission.stats.clientstats', diff --git a/www/js/diary/services.js b/www/js/diary/services.js index 7ebd6f115..d425a27b5 100644 --- a/www/js/diary/services.js +++ b/www/js/diary/services.js @@ -2,7 +2,7 @@ angular.module('emission.main.diary.services', ['emission.plugin.logger', 'emission.services', 'emission.main.common.services', - 'emission.incident.posttrip.manual', 'emission.tripconfirm.services']) + 'emission.incident.posttrip.manual', 'emission.survey.multilabel.services']) .factory('DiaryHelper', function(CommonGraph, PostTripManualMarker, $translate){ var dh = {}; // dh.expandEarlierOrLater = function(id) { diff --git a/www/js/goals.js b/www/js/goals.js index 9bed3b80b..8261b2fc0 100644 --- a/www/js/goals.js +++ b/www/js/goals.js @@ -2,7 +2,7 @@ angular.module('emission.main.goals',['emission.services', 'emission.plugin.logger', 'emission.plugin.kvstore', - 'emission.survey.launch', + 'emission.survey.external.launch', 'ngSanitize', 'ngAnimate', 'emission.splash.referral', 'ng-walkthrough', 'nzTour']) diff --git a/www/js/intro.js b/www/js/intro.js index 37a59803b..5cd3e8fe9 100644 --- a/www/js/intro.js +++ b/www/js/intro.js @@ -2,6 +2,7 @@ angular.module('emission.intro', ['emission.splash.startprefs', 'emission.splash.updatecheck', + 'emission.survey.external.launch', 'emission.i18n.utils', 'ionic-toast']) diff --git a/www/js/main.js b/www/js/main.js index c32526973..d0f49ba1a 100644 --- a/www/js/main.js +++ b/www/js/main.js @@ -7,7 +7,7 @@ angular.module('emission.main', ['emission.main.recent', 'emission.main.common', 'emission.main.heatmap', 'emission.main.metrics', - 'emission.tripconfirm.posttrip.map', + 'emission.survey.multilabel.posttrip.map', 'emission.services', 'emission.services.upload']) diff --git a/www/js/survey/launch.js b/www/js/survey/external/launch.js similarity index 99% rename from www/js/survey/launch.js rename to www/js/survey/external/launch.js index 99447ed59..7cef32b91 100644 --- a/www/js/survey/launch.js +++ b/www/js/survey/external/launch.js @@ -1,6 +1,6 @@ 'use strict'; -angular.module('emission.survey.launch', ['emission.services', +angular.module('emission.survey.external.launch', ['emission.services', 'emission.plugin.logger']) .factory('SurveyLaunch', function($http, $window, $ionicPopup, $rootScope, diff --git a/www/js/survey/time_insert.js b/www/js/survey/external/time_insert.js similarity index 100% rename from www/js/survey/time_insert.js rename to www/js/survey/external/time_insert.js diff --git a/www/js/survey/uuid_insert_id.js b/www/js/survey/external/uuid_insert_id.js similarity index 100% rename from www/js/survey/uuid_insert_id.js rename to www/js/survey/external/uuid_insert_id.js diff --git a/www/js/survey/uuid_insert_xpath.js b/www/js/survey/external/uuid_insert_xpath.js similarity index 100% rename from www/js/survey/uuid_insert_xpath.js rename to www/js/survey/external/uuid_insert_xpath.js diff --git a/www/js/diary/infinite_scroll_filters.js b/www/js/survey/multilabel/infinite_scroll_filters.js similarity index 94% rename from www/js/diary/infinite_scroll_filters.js rename to www/js/survey/multilabel/infinite_scroll_filters.js index ec57a4ee0..340542b83 100644 --- a/www/js/diary/infinite_scroll_filters.js +++ b/www/js/survey/multilabel/infinite_scroll_filters.js @@ -8,8 +8,8 @@ * All UI elements should only use $scope variables. */ -angular.module('emission.main.diary.infscrollfilters',[ - 'emission.tripconfirm.services', +angular.module('emission.survey.multilabel.infscrollfilters',[ + 'emission.survey.multilabel.services', 'emission.stats.clientstats', 'emission.plugin.logger' ]) diff --git a/www/js/tripconfirm/multi-label-ui.js b/www/js/survey/multilabel/multi-label-ui.js similarity index 99% rename from www/js/tripconfirm/multi-label-ui.js rename to www/js/survey/multilabel/multi-label-ui.js index a88a43aba..6b8b96541 100644 --- a/www/js/tripconfirm/multi-label-ui.js +++ b/www/js/survey/multilabel/multi-label-ui.js @@ -12,8 +12,8 @@ * other components. */ -angular.module('emission.tripconfirm.multilabel', - ['emission.tripconfirm.services', +angular.module('emission.survey.multilabel.buttons', + ['emission.survey.multilabel.services', 'emission.stats.clientstats', 'emission.main.diary.services']) .directive('multilabel', function() { diff --git a/www/js/tripconfirm/one-click-button.js b/www/js/survey/multilabel/one-click-button.js similarity index 91% rename from www/js/tripconfirm/one-click-button.js rename to www/js/survey/multilabel/one-click-button.js index 6cdedc9ff..3e9da871c 100644 --- a/www/js/tripconfirm/one-click-button.js +++ b/www/js/survey/multilabel/one-click-button.js @@ -1,5 +1,5 @@ -angular.module('emission.tripconfirm.verifycheck', - ['emission.tripconfirm.services', +angular.module('emission.survey.multilabel.verifycheck', + ['emission.survey.multilabel.services', 'emission.main.diary.services']) .directive('verifycheck', function($timeout) { return { diff --git a/www/js/tripconfirm/post-trip-map-display.js b/www/js/survey/multilabel/post-trip-map-display.js similarity index 98% rename from www/js/tripconfirm/post-trip-map-display.js rename to www/js/survey/multilabel/post-trip-map-display.js index 4d25a4a84..90c11fdcd 100644 --- a/www/js/tripconfirm/post-trip-map-display.js +++ b/www/js/survey/multilabel/post-trip-map-display.js @@ -1,8 +1,8 @@ 'use strict'; -angular.module('emission.tripconfirm.posttrip.map',['ui-leaflet', 'ng-walkthrough', +angular.module('emission.survey.multilabel.posttrip.map',['ui-leaflet', 'ng-walkthrough', 'emission.plugin.kvstore', 'emission.services', - 'emission.tripconfirm.services', + 'emission.survey.multilabel.services', 'emission.plugin.logger', 'emission.main.diary.services']) diff --git a/www/js/tripconfirm/post-trip-prompt.js b/www/js/survey/multilabel/post-trip-prompt.js similarity index 99% rename from www/js/tripconfirm/post-trip-prompt.js rename to www/js/survey/multilabel/post-trip-prompt.js index e9b011427..ecf173aa5 100644 --- a/www/js/tripconfirm/post-trip-prompt.js +++ b/www/js/survey/multilabel/post-trip-prompt.js @@ -1,6 +1,6 @@ 'use strict'; -angular.module('emission.tripconfirm.posttrip.prompt', ['emission.plugin.logger']) +angular.module('emission.survey.multilabel.posttrip.prompt', ['emission.plugin.logger']) .factory("PostTripAutoPrompt", function($window, $ionicPlatform, $rootScope, $state, $ionicPopup, Logger, $translate) { var ptap = {}; diff --git a/www/js/tripconfirm/trip-confirm-services.js b/www/js/survey/multilabel/trip-confirm-services.js similarity index 97% rename from www/js/tripconfirm/trip-confirm-services.js rename to www/js/survey/multilabel/trip-confirm-services.js index 8089362e5..baacdc8f0 100644 --- a/www/js/tripconfirm/trip-confirm-services.js +++ b/www/js/survey/multilabel/trip-confirm-services.js @@ -1,4 +1,4 @@ -angular.module('emission.tripconfirm.services', ['ionic', 'emission.i18n.utils', "emission.plugin.logger"]) +angular.module('emission.survey.multilabel.services', ['ionic', 'emission.i18n.utils', "emission.plugin.logger"]) .factory("ConfirmHelper", function($http, $ionicPopup, $translate, i18nUtils, Logger) { var ch = {}; ch.INPUTS = ["MODE", "PURPOSE"] From 5ac9e71cf8c0e3f6c187c4d20fd2f699e2ccc140 Mon Sep 17 00:00:00 2001 From: Shankari Date: Tue, 5 Oct 2021 08:14:36 -0700 Subject: [PATCH 025/175] Final round of renaming - We move out the templates from `tripconfirm` to `survey/multilabel` and change all the template loading code as well. - We also create a top layer `survey.js` which imports the relevant modules from the survey implementations. This allows the code which uses the values e.g. `list.js`, `infinite_scroll_list.js` and loads the survey dynamically, to include the survey module directly and not have to change it to switch between implementations. --- www/index.html | 1 + www/js/diary/infinite_scroll_list.js | 4 +--- www/js/diary/list.js | 3 +-- www/js/survey/multilabel/multi-label-ui.js | 4 ++-- www/js/survey/multilabel/one-click-button.js | 2 +- www/js/survey/survey.js | 14 ++++++++++++++ .../{tripconfirm => survey/multilabel}/map.html | 0 .../multilabel}/multi-label-ui.html | 0 .../multilabel}/one-click-button.html | 0 9 files changed, 20 insertions(+), 8 deletions(-) create mode 100644 www/js/survey/survey.js rename www/templates/{tripconfirm => survey/multilabel}/map.html (100%) rename www/templates/{tripconfirm => survey/multilabel}/multi-label-ui.html (100%) rename www/templates/{tripconfirm => survey/multilabel}/one-click-button.html (100%) diff --git a/www/index.html b/www/index.html index d24610d24..0d0c19f00 100644 --- a/www/index.html +++ b/www/index.html @@ -78,6 +78,7 @@ + diff --git a/www/js/diary/infinite_scroll_list.js b/www/js/diary/infinite_scroll_list.js index 5d8e7f8d7..f1455ca57 100644 --- a/www/js/diary/infinite_scroll_list.js +++ b/www/js/diary/infinite_scroll_list.js @@ -11,11 +11,9 @@ angular.module('emission.main.diary.infscrolllist',['ui-leaflet', 'ionic-datepicker', 'emission.main.common.services', - 'emission.survey.multilabel.buttons', - 'emission.survey.multilabel.verifycheck', 'emission.services', + 'emission.survey', 'ng-walkthrough', 'nzTour', 'emission.plugin.kvstore', - 'emission.survey.multilabel.infscrollfilters', 'emission.stats.clientstats', 'emission.plugin.logger']) diff --git a/www/js/diary/list.js b/www/js/diary/list.js index 3e4391c02..f77dc9ca1 100644 --- a/www/js/diary/list.js +++ b/www/js/diary/list.js @@ -11,9 +11,8 @@ angular.module('emission.main.diary.list',['ui-leaflet', 'ionic-datepicker', 'emission.main.common.services', - 'emission.survey.multilabel.buttons', - 'emission.survey.multilabel.verifycheck', 'emission.services', + 'emission.survey', 'ng-walkthrough', 'nzTour', 'emission.plugin.kvstore', 'emission.stats.clientstats', 'emission.plugin.logger' diff --git a/www/js/survey/multilabel/multi-label-ui.js b/www/js/survey/multilabel/multi-label-ui.js index 6b8b96541..211ac504e 100644 --- a/www/js/survey/multilabel/multi-label-ui.js +++ b/www/js/survey/multilabel/multi-label-ui.js @@ -23,7 +23,7 @@ angular.module('emission.survey.multilabel.buttons', unifiedConfirmsResults: "=", }, controller: "MultiLabelCtrl", - templateUrl: 'templates/tripconfirm/multi-label-ui.html' + templateUrl: 'templates/survey/multilabel/multi-label-ui.html' }; }) .controller("MultiLabelCtrl", function($scope, $element, $attrs, @@ -237,7 +237,7 @@ angular.module('emission.survey.multilabel.buttons', }) .factory("MultiLabelService", function(ConfirmHelper, DiaryHelper, $timeout) { var mls = {}; - + console.log("Creating MultiLabelService"); ConfirmHelper.inputParamsPromise.then((inputParams) => mls.inputParams = inputParams); /** diff --git a/www/js/survey/multilabel/one-click-button.js b/www/js/survey/multilabel/one-click-button.js index 3e9da871c..a31074c6a 100644 --- a/www/js/survey/multilabel/one-click-button.js +++ b/www/js/survey/multilabel/one-click-button.js @@ -9,7 +9,7 @@ angular.module('emission.survey.multilabel.verifycheck', invokedfrom: "=" }, controller: "OneClickButtonCtrl", - templateUrl: 'templates/tripconfirm/one-click-button.html' + templateUrl: 'templates/survey/multilabel/one-click-button.html' }; }) .controller("OneClickButtonCtrl", function($scope, $element, $attrs) { diff --git a/www/js/survey/survey.js b/www/js/survey/survey.js new file mode 100644 index 000000000..053b1a196 --- /dev/null +++ b/www/js/survey/survey.js @@ -0,0 +1,14 @@ +'use strict'; + +angular.module('emission.survey', [ + "emission.survey.external.launch", + "emission.survey.multilabel.buttons", + "emission.survey.multilabel.infscrollfilters", + ]) + +.factory("SurveyOptions", function() { + var surveyoptions = {}; + console.log("This is currently a NOP; we load the individual components dynamically"); + + return surveyoptions; +}); diff --git a/www/templates/tripconfirm/map.html b/www/templates/survey/multilabel/map.html similarity index 100% rename from www/templates/tripconfirm/map.html rename to www/templates/survey/multilabel/map.html diff --git a/www/templates/tripconfirm/multi-label-ui.html b/www/templates/survey/multilabel/multi-label-ui.html similarity index 100% rename from www/templates/tripconfirm/multi-label-ui.html rename to www/templates/survey/multilabel/multi-label-ui.html diff --git a/www/templates/tripconfirm/one-click-button.html b/www/templates/survey/multilabel/one-click-button.html similarity index 100% rename from www/templates/tripconfirm/one-click-button.html rename to www/templates/survey/multilabel/one-click-button.html From 3d315a3b76ad8b8a5afc3b3346c35ad7250ec777 Mon Sep 17 00:00:00 2001 From: Shankari Date: Tue, 5 Oct 2021 10:17:26 -0700 Subject: [PATCH 026/175] Final attempt at generalization for now - Create a "Config" in the top-level survey module for the multi-label survey - Switch the list views to use the configurations to figure the service and filters - Switch the HTML to use the configurations to the extent possible. This extent is the linkedtag attribute of the `verifycheck` element. Alas, we can't appear to set the element directive tag name directly (see ) https://github.com/e-mission/e-mission-docs/issues/674#issuecomment-934535259 to https://github.com/e-mission/e-mission-docs/issues/674#issuecomment-934575342 + move the one-click `verifycheck` button outside of `multilabel` since it is explicitly designed for use with other kinds of surveys as well --- www/index.html | 2 +- www/js/diary/infinite_scroll_list.js | 7 ++-- www/js/diary/list.js | 4 ++- www/js/survey/multilabel/one-click-button.js | 4 +-- www/js/survey/one-click-button.js | 32 +++++++++++++++++++ www/js/survey/survey.js | 6 ++++ www/templates/diary/infinite_scroll_list.html | 2 +- www/templates/diary/list.html | 2 +- .../{multilabel => }/one-click-button.html | 0 9 files changed, 50 insertions(+), 9 deletions(-) create mode 100644 www/js/survey/one-click-button.js rename www/templates/survey/{multilabel => }/one-click-button.html (100%) diff --git a/www/index.html b/www/index.html index 0d0c19f00..99aae8c85 100644 --- a/www/index.html +++ b/www/index.html @@ -79,13 +79,13 @@ + - diff --git a/www/js/diary/infinite_scroll_list.js b/www/js/diary/infinite_scroll_list.js index f1455ca57..7c8b851ec 100644 --- a/www/js/diary/infinite_scroll_list.js +++ b/www/js/diary/infinite_scroll_list.js @@ -23,22 +23,23 @@ angular.module('emission.main.diary.infscrolllist',['ui-leaflet', $ionicLoading, $ionicActionSheet, $timeout, - ionicDatePicker, leafletData, Timeline, CommonGraph, DiaryHelper, + SurveyOptions, Config, PostTripManualMarker, nzTour, KVStore, Logger, UnifiedDataLoader, $ionicPopover, $ionicModal, $translate) { // TODO: load only a subset of entries instead of everything console.log("controller InfiniteDiaryListCtrl called"); + $scope.surveyOpt = SurveyOptions.MULTILABEL; // Add option const placeLimiter = new Bottleneck({ maxConcurrent: 2, minTime: 500 }); $scope.data = {}; - $scope.tripFilterFactory = $injector.get("InfScrollFilters"); + $scope.tripFilterFactory = $injector.get($scope.surveyOpt.filter); $scope.filterInputs = $scope.tripFilterFactory.configuredFilters; - $scope.labelPopulateFactory = $injector.get("MultiLabelService"); + $scope.labelPopulateFactory = $injector.get($scope.surveyOpt.service); $scope.getActiveFilters = function() { return $scope.filterInputs.filter(sf => sf.state).map(sf => sf.key); diff --git a/www/js/diary/list.js b/www/js/diary/list.js index f77dc9ca1..ad8a008ca 100644 --- a/www/js/diary/list.js +++ b/www/js/diary/list.js @@ -25,12 +25,14 @@ angular.module('emission.main.diary.list',['ui-leaflet', $ionicActionSheet, ionicDatePicker, leafletData, Timeline, CommonGraph, DiaryHelper, + SurveyOptions, Config, PostTripManualMarker, nzTour, KVStore, Logger, UnifiedDataLoader, $ionicPopover, $translate) { console.log("controller DiaryListCtrl called"); + $scope.surveyOpt = SurveyOptions.MULTILABEL; ClientStats.addReading(ClientStats.getStatKeys().LABEL_TAB_SWITCH, {"source": null, "dest": $scope.data? $scope.data.currDay : undefined}); // Add option - $scope.labelPopulateFactory = $injector.get("MultiLabelService"); + $scope.labelPopulateFactory = $injector.get($scope.surveyOpt.service); var readAndUpdateForDay = function(day) { // This just launches the update. The update can complete in the background diff --git a/www/js/survey/multilabel/one-click-button.js b/www/js/survey/multilabel/one-click-button.js index a31074c6a..0426585a6 100644 --- a/www/js/survey/multilabel/one-click-button.js +++ b/www/js/survey/multilabel/one-click-button.js @@ -9,12 +9,12 @@ angular.module('emission.survey.multilabel.verifycheck', invokedfrom: "=" }, controller: "OneClickButtonCtrl", - templateUrl: 'templates/survey/multilabel/one-click-button.html' + templateUrl: 'templates/survey/one-click-button.html' }; }) .controller("OneClickButtonCtrl", function($scope, $element, $attrs) { var findLinkedLabelScope = function() { - console.log("$element is ", $element); + console.log("$element is ", $element, "linkedtag is ",$scope.linkedTag); console.log("parent row is", $element.parents("ion-item")); let rowElement = $element.parents("ion-item") console.log("row Element is", rowElement); diff --git a/www/js/survey/one-click-button.js b/www/js/survey/one-click-button.js new file mode 100644 index 000000000..cb8ac73a5 --- /dev/null +++ b/www/js/survey/one-click-button.js @@ -0,0 +1,32 @@ +angular.module('emission.survey.multilabel.verifycheck', + ['emission.survey.multilabel.services', + 'emission.main.diary.services']) +.directive('verifycheck', function($timeout) { + return { + scope: { + linkedtag: "@", + trip: "=", + invokedfrom: "=" + }, + controller: "OneClickButtonCtrl", + templateUrl: 'templates/survey/multilabel/one-click-button.html' + }; +}) +.controller("OneClickButtonCtrl", function($scope, $element, $attrs) { + var findLinkedLabelScope = function() { + console.log("$element is ", $element, "linkedtag is ",$scope.linkedTag); + console.log("parent row is", $element.parents("ion-item")); + let rowElement = $element.parents("ion-item") + console.log("row Element is", rowElement); + let linkedlabel = rowElement.find($scope.linkedtag); + console.log("child linkedlabel is", linkedlabel); + let linkedlabelScope = angular.element(linkedlabel).isolateScope(); + console.log("linkedlabel scope is", linkedlabelScope); + return linkedlabelScope; + }; + + $scope.verifyTrip = function() { + let linkedLabelScope = findLinkedLabelScope(); + linkedLabelScope.verifyTrip(); + } +}); diff --git a/www/js/survey/survey.js b/www/js/survey/survey.js index 053b1a196..95fa6fb33 100644 --- a/www/js/survey/survey.js +++ b/www/js/survey/survey.js @@ -3,12 +3,18 @@ angular.module('emission.survey', [ "emission.survey.external.launch", "emission.survey.multilabel.buttons", + "emission.survey.multilabel.verifycheck", "emission.survey.multilabel.infscrollfilters", ]) .factory("SurveyOptions", function() { var surveyoptions = {}; console.log("This is currently a NOP; we load the individual components dynamically"); + surveyoptions.MULTILABEL = { + filter: "InfScrollFilters", + service: "MultiLabelService", + elementTag: "multilabel" + } return surveyoptions; }); diff --git a/www/templates/diary/infinite_scroll_list.html b/www/templates/diary/infinite_scroll_list.html index f950c85f7..689c8efb3 100644 --- a/www/templates/diary/infinite_scroll_list.html +++ b/www/templates/diary/infinite_scroll_list.html @@ -72,7 +72,7 @@

{{'diary.scroll-to-load-more' | transla {{trip.end_display_name}} -
diff --git a/www/templates/diary/list.html b/www/templates/diary/list.html index 3d685797b..3195ab15d 100644 --- a/www/templates/diary/list.html +++ b/www/templates/diary/list.html @@ -87,7 +87,7 @@
- +
diff --git a/www/templates/survey/multilabel/one-click-button.html b/www/templates/survey/one-click-button.html similarity index 100% rename from www/templates/survey/multilabel/one-click-button.html rename to www/templates/survey/one-click-button.html From e8f8a0c3aad819942ffab415e3335df9fb808aef Mon Sep 17 00:00:00 2001 From: Shankari Date: Tue, 5 Oct 2021 10:51:10 -0700 Subject: [PATCH 027/175] Really final set of updates - Remove the old one-click-button!! - Change the module name - Remove unnecessary dependencies Current hardcoded status is: ``` grep -r multilabel www/ | egrep -v "survey/multilabel|posttrip" www//js/survey/survey.js: "emission.survey.multilabel.buttons", www//js/survey/survey.js: "emission.survey.multilabel.infscrollfilters", www//js/survey/survey.js: elementTag: "multilabel" www//templates/diary/list.html: www//templates/diary/infinite_scroll_list.html: ``` --- www/js/survey/multilabel/one-click-button.js | 32 -------------------- www/js/survey/one-click-button.js | 4 +-- www/js/survey/survey.js | 2 +- 3 files changed, 2 insertions(+), 36 deletions(-) delete mode 100644 www/js/survey/multilabel/one-click-button.js diff --git a/www/js/survey/multilabel/one-click-button.js b/www/js/survey/multilabel/one-click-button.js deleted file mode 100644 index 0426585a6..000000000 --- a/www/js/survey/multilabel/one-click-button.js +++ /dev/null @@ -1,32 +0,0 @@ -angular.module('emission.survey.multilabel.verifycheck', - ['emission.survey.multilabel.services', - 'emission.main.diary.services']) -.directive('verifycheck', function($timeout) { - return { - scope: { - linkedtag: "@", - trip: "=", - invokedfrom: "=" - }, - controller: "OneClickButtonCtrl", - templateUrl: 'templates/survey/one-click-button.html' - }; -}) -.controller("OneClickButtonCtrl", function($scope, $element, $attrs) { - var findLinkedLabelScope = function() { - console.log("$element is ", $element, "linkedtag is ",$scope.linkedTag); - console.log("parent row is", $element.parents("ion-item")); - let rowElement = $element.parents("ion-item") - console.log("row Element is", rowElement); - let linkedlabel = rowElement.find($scope.linkedtag); - console.log("child linkedlabel is", linkedlabel); - let linkedlabelScope = angular.element(linkedlabel).isolateScope(); - console.log("linkedlabel scope is", linkedlabelScope); - return linkedlabelScope; - }; - - $scope.verifyTrip = function() { - let linkedLabelScope = findLinkedLabelScope(); - linkedLabelScope.verifyTrip(); - } -}); diff --git a/www/js/survey/one-click-button.js b/www/js/survey/one-click-button.js index cb8ac73a5..57657b4d3 100644 --- a/www/js/survey/one-click-button.js +++ b/www/js/survey/one-click-button.js @@ -1,6 +1,4 @@ -angular.module('emission.survey.multilabel.verifycheck', - ['emission.survey.multilabel.services', - 'emission.main.diary.services']) +angular.module('emission.survey.verifycheck', []) .directive('verifycheck', function($timeout) { return { scope: { diff --git a/www/js/survey/survey.js b/www/js/survey/survey.js index 95fa6fb33..f2ae01cf4 100644 --- a/www/js/survey/survey.js +++ b/www/js/survey/survey.js @@ -1,9 +1,9 @@ 'use strict'; angular.module('emission.survey', [ + "emission.survey.verifycheck", "emission.survey.external.launch", "emission.survey.multilabel.buttons", - "emission.survey.multilabel.verifycheck", "emission.survey.multilabel.infscrollfilters", ]) From 25513378b7a8d785cf846b6b6713fd085f903a34 Mon Sep 17 00:00:00 2001 From: Shankari Date: Tue, 5 Oct 2021 11:15:46 -0700 Subject: [PATCH 028/175] Final cleanup fixes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Remove logging that happens on every directive init to improve performance - Fix the template URL for the verify button - Fix the case on the `linkedTag` - Remove unused scope variables from the verify button, both in the definition and in the usage Testing done: Clicked the verify button; it worked $element is S.fn.init [verifycheck.row] linkedtag is multilabel index.html:145 parent row is S.fn.init [ion-item#diary-item.list-item.item, prevObject: S.fn.init(1)] index.html:145 row Element is S.fn.init [ion-item#diary-item.list-item.item, prevObject: S.fn.init(1)] index.html:145 child linkedlabel is S.fn.init [multilabel.col, prevObject: S.fn.init(1)] index.html:145 linkedlabel scope is Scope {$id: 194, $$childTail: Scope, $$childHead: Scope, $$prevSibling: Scope, $$nextSibling: Scope, …} index.html:145 About to verify trip 1470341031.235 -> 1470342912 with current visibilityalready-verified $element is S.fn.init [verifycheck.col-10.diarycheckmark-container.center-vert.center-horiz] linkedtag is multilabel index.html:145 parent row is S.fn.init [ion-item#diary-item.list-item.item, prevObject: S.fn.init(1)] index.html:145 row Element is S.fn.init [ion-item#diary-item.list-item.item, prevObject: S.fn.init(1)] index.html:145 child linkedlabel is S.fn.init [multilabel.col, prevObject: S.fn.init(1)] index.html:145 linkedlabel scope is Scope {$id: 2258, $$childTail: Scope, $$childHead: Scope, $$prevSibling: Scope, $$nextSibling: null, …} index.html:145 About to verify trip 1470882349.3511817 -> 1470883723.49 with current visibilityalready-verified --- www/js/survey/multilabel/multi-label-ui.js | 10 +++++----- www/js/survey/one-click-button.js | 6 ++---- www/templates/diary/infinite_scroll_list.html | 2 +- www/templates/diary/list.html | 2 +- 4 files changed, 9 insertions(+), 11 deletions(-) diff --git a/www/js/survey/multilabel/multi-label-ui.js b/www/js/survey/multilabel/multi-label-ui.js index 211ac504e..65d5258c6 100644 --- a/www/js/survey/multilabel/multi-label-ui.js +++ b/www/js/survey/multilabel/multi-label-ui.js @@ -31,22 +31,22 @@ angular.module('emission.survey.multilabel.buttons', console.log("Invoked multilabel directive controller for labels "+ConfirmHelper.INPUTS); var findViewElement = function() { - console.log("$element is ", $element); - console.log("parent row is", $element.parents("ion-item")); + // console.log("$element is ", $element); + // console.log("parent row is", $element.parents("ion-item")); let rowElement = $element.parents("ion-view") - console.log("row Element is", rowElement); + // console.log("row Element is", rowElement); return angular.element(rowElement); } var findViewState = function() { let viewState = findViewElement().attr("state") - console.log("view state is ", viewState); + // console.log("view state is ", viewState); return viewState; } var findViewScope = function() { let viewScope = findViewElement().scope(); - console.log("view scope is ", viewScope); + // console.log("view scope is ", viewScope); return viewScope; } diff --git a/www/js/survey/one-click-button.js b/www/js/survey/one-click-button.js index 57657b4d3..79dbbc771 100644 --- a/www/js/survey/one-click-button.js +++ b/www/js/survey/one-click-button.js @@ -3,16 +3,14 @@ angular.module('emission.survey.verifycheck', []) return { scope: { linkedtag: "@", - trip: "=", - invokedfrom: "=" }, controller: "OneClickButtonCtrl", - templateUrl: 'templates/survey/multilabel/one-click-button.html' + templateUrl: 'templates/survey/one-click-button.html' }; }) .controller("OneClickButtonCtrl", function($scope, $element, $attrs) { var findLinkedLabelScope = function() { - console.log("$element is ", $element, "linkedtag is ",$scope.linkedTag); + console.log("$element is ", $element, "linkedtag is ",$scope.linkedtag); console.log("parent row is", $element.parents("ion-item")); let rowElement = $element.parents("ion-item") console.log("row Element is", rowElement); diff --git a/www/templates/diary/infinite_scroll_list.html b/www/templates/diary/infinite_scroll_list.html index 689c8efb3..fa00230e8 100644 --- a/www/templates/diary/infinite_scroll_list.html +++ b/www/templates/diary/infinite_scroll_list.html @@ -72,7 +72,7 @@

{{'diary.scroll-to-load-more' | transla {{trip.end_display_name}} -
diff --git a/www/templates/diary/list.html b/www/templates/diary/list.html index 3195ab15d..a55015e6f 100644 --- a/www/templates/diary/list.html +++ b/www/templates/diary/list.html @@ -87,7 +87,7 @@
- +
From 19d03cd51abc3754c2e38f0d80cf7bca53003c3d Mon Sep 17 00:00:00 2001 From: Shankari Date: Tue, 5 Oct 2021 20:32:18 -0700 Subject: [PATCH 029/175] Finally get the survey to also be dynamic This is a bit hacky because it assumes that the only input is the trip object. There are likely ways to get around it through clever dom manipulation by using the `link` method but I am not going to overengineer here. This is basically the `ng-if` idea outlined in: https://github.com/e-mission/e-mission-docs/issues/674#issuecomment-934575342 --- www/js/survey/survey.js | 9 +++++++++ www/templates/diary/infinite_scroll_list.html | 2 +- www/templates/diary/list.html | 2 +- www/templates/survey/wrapper.html | 2 ++ 4 files changed, 13 insertions(+), 2 deletions(-) create mode 100644 www/templates/survey/wrapper.html diff --git a/www/js/survey/survey.js b/www/js/survey/survey.js index f2ae01cf4..4ee6a604f 100644 --- a/www/js/survey/survey.js +++ b/www/js/survey/survey.js @@ -17,4 +17,13 @@ angular.module('emission.survey', [ } return surveyoptions; +}) +.directive("linkedsurvey", function($compile) { + return { + scope: { + elementTag:"@", + trip: "=", + }, + templateUrl: "templates/survey/wrapper.html", + }; }); diff --git a/www/templates/diary/infinite_scroll_list.html b/www/templates/diary/infinite_scroll_list.html index fa00230e8..f172e4d42 100644 --- a/www/templates/diary/infinite_scroll_list.html +++ b/www/templates/diary/infinite_scroll_list.html @@ -80,7 +80,7 @@

{{'diary.scroll-to-load-more' | transla filled in outside the directive to filter properly e.g. https://github.com/e-mission/e-mission-docs/issues/674#issuecomment-933083710 --> - + diff --git a/www/templates/diary/list.html b/www/templates/diary/list.html index a55015e6f..51085f1af 100644 --- a/www/templates/diary/list.html +++ b/www/templates/diary/list.html @@ -92,7 +92,7 @@
- +
diff --git a/www/templates/survey/wrapper.html b/www/templates/survey/wrapper.html new file mode 100644 index 000000000..eb3a522cb --- /dev/null +++ b/www/templates/survey/wrapper.html @@ -0,0 +1,2 @@ + + From d9cc13bbc38197f6577044a911ef2e68f9b86519 Mon Sep 17 00:00:00 2001 From: Shankari Date: Tue, 5 Oct 2021 23:39:59 -0700 Subject: [PATCH 030/175] Copy over the inferred labels to match the code Copy over the existing user input and user inferred labels from the trip properties to the top level. This allows the existing inference code to work without any changes. Yay! --- www/js/diary/list.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/www/js/diary/list.js b/www/js/diary/list.js index ad8a008ca..597cd1e81 100644 --- a/www/js/diary/list.js +++ b/www/js/diary/list.js @@ -215,7 +215,8 @@ angular.module('emission.main.diary.list',['ui-leaflet', // trip object so that the unified populate code works tripgj.start_ts = tripgj.data.properties.start_ts; tripgj.end_ts = tripgj.data.properties.end_ts; - tripgj.inferred_labels = []; + tripgj.inferred_labels = tripgj.data.properties.inferred_labels; + tripgj.user_input = tripgj.data.properties.user_input; $scope.labelPopulateFactory.populateInputsAndInferences(tripgj, $scope.data.unifiedConfirmsResults); $scope.populateCommonInfo(tripgj); }); From 4ac493cb9e6c7020ed7e1f40f570279c6a09b2cc Mon Sep 17 00:00:00 2001 From: Shankari Date: Wed, 6 Oct 2021 09:25:28 -0700 Subject: [PATCH 031/175] Fix the `verifyTrip` code to use `$scope.trip` instead of `trip` Since the variable is no longer passed in. And it can't be passed in because the `verifyTrip` is actually invoked from outside this scope by the `verifycheck` directive. We couldn't test this before because all the trips were already with green labels. Tested with a yellow label and it worked. --- www/js/survey/multilabel/multi-label-ui.js | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/www/js/survey/multilabel/multi-label-ui.js b/www/js/survey/multilabel/multi-label-ui.js index 65d5258c6..59dfabfb7 100644 --- a/www/js/survey/multilabel/multi-label-ui.js +++ b/www/js/survey/multilabel/multi-label-ui.js @@ -78,19 +78,19 @@ angular.module('emission.survey.multilabel.buttons', ClientStats.addReading(ClientStats.getStatKeys().VERIFY_TRIP, {"verifiable": true, "currView": $scope.currentViewState, - "userInput": angular.toJson(trip.userInput), - "finalInference": angular.toJson(trip.finalInference)}); + "userInput": angular.toJson($scope.trip.userInput), + "finalInference": angular.toJson($scope.trip.finalInference)}); $scope.draftInput = { - "start_ts": trip.start_ts, - "end_ts": trip.end_ts + "start_ts": $scope.trip.start_ts, + "end_ts": $scope.trip.end_ts }; - $scope.editingTrip = trip; + $scope.editingTrip = $scope.trip; for (const inputType of ConfirmHelper.INPUTS) { - const inferred = trip.finalInference[inputType]; + const inferred = $scope.trip.finalInference[inputType]; // TODO: figure out what to do with "other". For now, do not verify. - if (inferred && !trip.userInput[inputType] && inferred != "other") $scope.store(inputType, inferred, false); + if (inferred && !$scope.trip.userInput[inputType] && inferred != "other") $scope.store(inputType, inferred, false); } } From f3ea875f28fd865d6c740d5c14929e50b2eb693b Mon Sep 17 00:00:00 2001 From: Shankari Date: Thu, 7 Oct 2021 10:09:53 -0700 Subject: [PATCH 032/175] Refactor the retrieval code for simplicity and performance Simplify the retrieval code by: - pulling out duplicated code from the original call and the local fallback into a separate function (`readTripsAndUnprocessedInputs`) - pulling out the processing of the trips and the manual input handling for future unification with the labeling code - in the common case, only read inputs *after* the pipeline is complete. Due to https://github.com/e-mission/e-mission-server/pull/837, the geojson trips should also now have any prior user inputs included in the trip. This plugs a huge performance issue for longitudinal data collection, because otherwise, we were reading the entire list of user inputs from the beginning of the install, which grows unboundedly. with this change, we will only read inputs from the timeline run point to now, which is bounded, and should be short depending on how frequently the timeline runs. This addresses: https://github.com/e-mission/e-mission-docs/issues/674#issuecomment-936653240 --- www/js/diary/services.js | 121 ++++++++++++++++++++------------------- 1 file changed, 61 insertions(+), 60 deletions(-) diff --git a/www/js/diary/services.js b/www/js/diary/services.js index d425a27b5..ba133174a 100644 --- a/www/js/diary/services.js +++ b/www/js/diary/services.js @@ -1110,34 +1110,20 @@ angular.module('emission.main.diary.services', ['emission.plugin.logger', var localCacheReadFn = timeline.updateFromDatabase; - // Functions - timeline.updateForDay = function(day) { // currDay is a moment - // First, we try the server - var tripsFromServerPromise = timeline.updateFromServer(day); - var isProcessingCompletePromise = timeline.isProcessingComplete(day); - - // Also mode/purpose and (currently disabled) survey answers - var tq = $window.cordova.plugins.BEMUserCache.getAllTimeQuery(); - var manualPromises = ConfirmHelper.INPUTS.map(function(inp) { - return UnifiedDataLoader.getUnifiedMessagesForInterval( - ConfirmHelper.inputDetails[inp].key, tq); - }); - // var surveyAnswersPromise = EnketoSurvey.getAllSurveyAnswers("manual/confirm_survey", { populateLabels: true }); - - // Deal with all the trip retrieval - Promise.all([tripsFromServerPromise, isProcessingCompletePromise].concat(manualPromises)) - .then(function([processedTripList, completeStatus, ...manualResults]) { - console.log("Promise.all() finished successfully with length " - +processedTripList.length+" completeStatus = "+completeStatus); - var mrString = 'with ' + manualResults.map(function(item, index) { - return ' ${mr.length} ${ConfirmHelper.INPUTS[index]}'; - }); + var processManualInputs = function(manualResults) { + var mrString = 'unprocessed manual inputs ' + + manualResults.map(function(item, index) { + return ` ${item.length} ${ConfirmHelper.INPUTS[index]}`; + }); console.log(mrString); - var tripList = processedTripList; timeline.data.unifiedConfirmsResults = {} manualResults.forEach(function(mr, index) { timeline.data.unifiedConfirmsResults[ConfirmHelper.INPUTS[index]] = mr; }); + } + + var addUnprocessedTrips = function(processedTripList, day, completeStatus) { + var tripList = processedTripList; if (!completeStatus) { return timeline.readUnprocessedTrips(day, processedTripList) .then(function(unprocessedTripList) { @@ -1150,46 +1136,61 @@ angular.module('emission.main.diary.services', ['emission.plugin.logger', } else { return tripList; } - }).then(function(combinedTripList) { - processOrDisplayNone(day, combinedTripList); - }).catch(function(error) { - // If there is any error reading from the server, we fallback on the local cache - Logger.log("while reading data from server for "+day +" error = "+JSON.stringify(error)); - console.log("About to hide loading overlay"); - $ionicLoading.hide(); - - var tripsFromCachePromise = localCacheReadFn(day); + } - // Also mode/purpose and (currently disabled) survey answers - var tq = $window.cordova.plugins.BEMUserCache.getAllTimeQuery(); - var manualPromises = ConfirmHelper.INPUTS.map(function(inp) { - return UnifiedDataLoader.getUnifiedMessagesForInterval( + var readTripsAndUnprocessedInputs = function(day, tripReadFn, completeStatus, tq) { + var manualPromises = ConfirmHelper.INPUTS.map(function(inp) { + return UnifiedDataLoader.getUnifiedMessagesForInterval( ConfirmHelper.inputDetails[inp].key, tq); - }); - Promise.all([tripsFromCachePromise].concat(manualPromises)).then(function( - [processedTripList, ...manualResults]) { - console.log(' in local cache, found ${modes.length} modes, ${purposes.length} purposes'); - var tripList = processedTripList; - timeline.data.unifiedConfirmsResults = {} - manualResults.forEach(function(mr, index) { - timeline.data.unifiedConfirmsResults[ConfirmHelper.INPUTS[index]] = mr; - }); - return timeline.readUnprocessedTrips(day, processedTripList) - .then(function(unprocessedTripList) { - Logger.log("tripList.length = "+tripList.length - +"unprocessedTripList.length = "+unprocessedTripList.length); - Array.prototype.push.apply(tripList, unprocessedTripList); - console.log("After merge, returning trip list of size "+tripList.length); - return tripList; - }) - }).then(function(combinedTripList) { - processOrDisplayNone(day, combinedTripList); - }).catch(function(error) { - console.log("About to hide loading overlay"); - $ionicLoading.hide(); - Logger.displayError("while reading data from cache for "+day, error); - }) }); + let tripsReadPromise = tripReadFn(day); + // var surveyAnswersPromise = EnketoSurvey.getAllSurveyAnswers("manual/confirm_survey", { populateLabels: true }); + let allManualPromise = Promise.all(manualPromises).then(processManualInputs); + + let allTripsPromise = tripsReadPromise.then((processedTripList) => { + console.log("Reading trips from server finished successfully with length " + +processedTripList.length+" completeStatus = "+completeStatus); + return addUnprocessedTrips(processedTripList, completeStatus); + }).then((combinedTripList) => processOrDisplayNone(day, combinedTripList)); + return Promise.all([allManualPromise, allTripsPromise]).then(() => { + console.log("Finished reading processed/unprocessed trips with length " + +timeline.data.currDayTrips.length); + }); + } + + // Functions + timeline.updateForDay = function(day) { // currDay is a moment + // First, we try the server + var isProcessingCompletePromise = timeline.isProcessingComplete(day); + + // First get the pipeline complete timestamp + isProcessingCompletePromise.then((completeTs, completeStatus) => { + // then, in parallel, read unprocessed user inputs + // and trips + // Also mode/purpose and (currently disabled) survey answers + var pendingTq = { + key: "write_ts", + startTs: completeTs, + endTs: moment().unix() + }; + readTripsAndUnprocessedInputs(day, timeline.updateFromServer, + completeStatus, pendingTq) + .catch(function(error) { + // If there is any error reading from the server, we fallback on the local cache + Logger.log("while reading data from server for "+day +" error = "+JSON.stringify(error)); + console.log("About to hide loading overlay"); + $ionicLoading.hide(); + + // Also mode/purpose and (currently disabled) survey answers + let allTq = $window.cordova.plugins.BEMUserCache.getAllTimeQuery(); + readTripsAndUnprocessedInputs(day, localCacheReadFn, undefined, allTq) + .catch(function(error) { + console.log("About to hide loading overlay"); + $ionicLoading.hide(); + Logger.displayError("while reading data from cache for "+day, error); + }) + }); + }); } timeline.getTrip = function(tripId) { From 5cd55dd62fd6fd37423e79663adbe946083e1622 Mon Sep 17 00:00:00 2001 From: John Leyden Date: Mon, 26 Feb 2018 14:15:03 -0800 Subject: [PATCH 033/175] notification open reading --- www/js/stats/clientstats.js | 4 +++- www/js/survey/external/launch.js | 7 ++++++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/www/js/stats/clientstats.js b/www/js/stats/clientstats.js index 1c1f97276..084b12ad2 100644 --- a/www/js/stats/clientstats.js +++ b/www/js/stats/clientstats.js @@ -19,7 +19,9 @@ angular.module('emission.stats.clientstats', []) INF_SCROLL_TIME: "inf_scroll_time", VERIFY_TRIP: "verify_trip", LABEL_TAB_SWITCH: "label_tab_switch", - SELECT_LABEL: "select_label" + SELECT_LABEL: "select_label", + EXPANDED_TRIP: "expanded_trip", + NOTIFICATION_OPEN: "notification_open" }; } diff --git a/www/js/survey/external/launch.js b/www/js/survey/external/launch.js index 7cef32b91..0a3e8c31c 100644 --- a/www/js/survey/external/launch.js +++ b/www/js/survey/external/launch.js @@ -1,7 +1,8 @@ 'use strict'; angular.module('emission.survey.external.launch', ['emission.services', - 'emission.plugin.logger']) + 'emission.plugin.logger', + 'emission.stats.clientstats']) .factory('SurveyLaunch', function($http, $window, $ionicPopup, $rootScope, CommHelper, Logger) { @@ -212,6 +213,10 @@ angular.module('emission.survey.external.launch', ['emission.services', surveylaunch.init = function() { $rootScope.$on('cloud:push:notification', function(event, data) { + ClientStats.addEvent(ClientStats.getStatKeys().NOTIFICATION_OPEN).then( + function() { + console.log("Added "+ClientStats.getStatKeys().NOTIFICATION_OPEN+" event. Data = " JSON.stringify(data)); + }); Logger.log("data = "+JSON.stringify(data)); if (angular.isDefined(data.additionalData) && angular.isDefined(data.additionalData.payload) && From 78a93698ca558f96e0ba45b7dedde264147bb934 Mon Sep 17 00:00:00 2001 From: Shankari Date: Thu, 14 Oct 2021 11:08:54 -0700 Subject: [PATCH 034/175] Fix formatting error from previous commit Previous commit was the cherry-picked 5cd55dd62fd6fd37423e79663adbe946083e1622 --- www/js/survey/external/launch.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/www/js/survey/external/launch.js b/www/js/survey/external/launch.js index 0a3e8c31c..1ea4c44c9 100644 --- a/www/js/survey/external/launch.js +++ b/www/js/survey/external/launch.js @@ -215,7 +215,7 @@ angular.module('emission.survey.external.launch', ['emission.services', $rootScope.$on('cloud:push:notification', function(event, data) { ClientStats.addEvent(ClientStats.getStatKeys().NOTIFICATION_OPEN).then( function() { - console.log("Added "+ClientStats.getStatKeys().NOTIFICATION_OPEN+" event. Data = " JSON.stringify(data)); + console.log("Added "+ClientStats.getStatKeys().NOTIFICATION_OPEN+" event. Data = " + JSON.stringify(data)); }); Logger.log("data = "+JSON.stringify(data)); if (angular.isDefined(data.additionalData) && From ac9b816034fe6596ad856d7ccabbb34a67b19a54 Mon Sep 17 00:00:00 2001 From: Shankari Date: Thu, 14 Oct 2021 11:29:30 -0700 Subject: [PATCH 035/175] [diary only] Support both imperial and metric units with a config option **Note that this currently works only for the diary**. The dashboard has not been fixed because it is not currently visible in the CEO branch :) My original plan was to only support metric units, since https://en.wikipedia.org/wiki/Metrication "According to the U.S. Central Intelligence Agency's online The World Factbook (2016), the only countries that have not adopted the metric system are Myanmar (also known as Burma), Liberia and the United States." However, it looks like this project will be US-focused for the forseeable future, and even the UK is beginning to revert its metrication process. So we will support both imperial and metric units with a config option. - Create a new service for this conversion - Have it use metric or imperial based on a config flag - Change all existing distance calculations to use the new service - Add a "suffix" to the service to distinguish between "mi" (miles) and "km" (kilometers) - Change all the templates and the i18n to use the suffix instead of hardcoded values Testing done: - set the config value to false; confirmed that everything is in km - set the config value to true; confirmed that everything is in miles and there were no errors in the console log --- www/i18n/en.json | 6 +-- www/index.html | 1 + www/js/config/imperial.js | 42 +++++++++++++++++++ www/js/diary/detail.js | 26 ++++-------- www/js/diary/infinite_scroll_list.js | 6 ++- www/js/diary/list.js | 6 ++- www/js/diary/services.js | 28 ------------- www/templates/diary/detail.html | 4 +- www/templates/diary/infinite_scroll_list.html | 2 +- www/templates/diary/list.html | 2 +- 10 files changed, 65 insertions(+), 58 deletions(-) create mode 100644 www/js/config/imperial.js diff --git a/www/i18n/en.json b/www/i18n/en.json index 53ccc31c6..1cb3109d0 100644 --- a/www/i18n/en.json +++ b/www/i18n/en.json @@ -145,8 +145,8 @@ "began": "Began {{startTime}}", "report-incident": "Report Incident", "draft": "DRAFT", - "distance-in-time": "{{distance}} km in {{time}}", - "date-distance-in-time": "{{date}}: {{distance}} km in {{time}}", + "distance-in-time": "{{distance}} {{distsuffix}} in {{time}}", + "date-distance-in-time": "{{date}}: {{distance}} {{distsuffix}} in {{time}}", "distance": "Distance", "time": "Time", "mode": "Mode", @@ -256,7 +256,7 @@ "details":{ "speed": "Speed", - "time": "Temps", + "time": "Time", "tour-detail-content": "To report an incident, zoom in as much as possible to the location where the incident occurred and click on the trip to mark a ☻ or ☹ incident", "tour-sectionList-content": "Trip sections, along with times and modes", "tour-sectionPct-content": "% of time spent in each mode for this trip" diff --git a/www/index.html b/www/index.html index 99aae8c85..baea9c3e1 100644 --- a/www/index.html +++ b/www/index.html @@ -64,6 +64,7 @@ + diff --git a/www/js/config/imperial.js b/www/js/config/imperial.js new file mode 100644 index 000000000..8c040caf1 --- /dev/null +++ b/www/js/config/imperial.js @@ -0,0 +1,42 @@ +'use strict'; + +angular.module('emission.config.imperial', ['emission.plugin.logger']) +.factory('ImperialConfig', function() { + // change to true if we want to use imperial units such as miles + // I didn't want to do this since the US is one of the only countries that + // still uses imperial units, but it looks like this will primarily be + // funded by a US source, so I guess we have to support this for now. + + // TODO: Convert this to a config option when we use config stuff + const USE_IMPERIAL = false; + const KM_TO_MILES = 0.621371; + + var ic = {} + + ic.getFormattedDistanceInKm = function(dist_in_meters) { + if (dist_in_meters > 1000) { + return (dist_in_meters/1000).toFixed(0); + } else { + return (dist_in_meters/1000).toFixed(3); + } + } + + ic.getFormattedDistanceInMiles = function(dist_in_meters) { + return (KM_TO_MILES * ic.getFormattedDistanceInKm(dist_in_meters)).toFixed(1); + } + + ic.getKmph = function(section) { + var metersPerSec = section.properties.distance / section.properties.duration; + return (metersPerSec * 3.6).toFixed(2); + }; + + ic.getMph = function(section) { + return (KM_TO_MILES * ic.getKmph(section)); + }; + + ic.getFormattedDistance = USE_IMPERIAL? ic.getFormattedDistanceInMiles : ic.getFormattedDistanceInKm; + ic.getFormattedSpeed = USE_IMPERIAL? ic.getMph : ic.getKmph; + ic.getDistanceSuffix = USE_IMPERIAL? "mi" : "km"; + ic.getSpeedSuffix = USE_IMPERIAL? "mph" : "kmph"; + return ic; +}); diff --git a/www/js/diary/detail.js b/www/js/diary/detail.js index 4f5794275..b75c121c8 100644 --- a/www/js/diary/detail.js +++ b/www/js/diary/detail.js @@ -1,12 +1,14 @@ 'use strict'; angular.module('emission.main.diary.detail',['ui-leaflet', 'ng-walkthrough', 'nvd3', 'emission.plugin.kvstore', - 'emission.services', 'emission.plugin.logger', + 'emission.services', + 'emission.config.imperial', + 'emission.plugin.logger', 'emission.incident.posttrip.manual']) .controller("DiaryDetailCtrl", function($scope, $rootScope, $window, $stateParams, $ionicActionSheet, leafletData, leafletMapEvents, nzTour, KVStore, - Logger, Timeline, DiaryHelper, Config, + Logger, Timeline, DiaryHelper, Config, ImperialConfig, CommHelper, PostTripManualMarker, $translate) { console.log("controller DiaryDetailCtrl called with params = "+ JSON.stringify($stateParams)); @@ -47,28 +49,14 @@ angular.module('emission.main.diary.detail',['ui-leaflet', 'ng-walkthrough', $scope.$broadcast('invalidateSize'); }; - $scope.getFormattedDate = DiaryHelper.getFormattedDate; - $scope.arrowColor = DiaryHelper.arrowColor; - $scope.parseEarlierOrLater = DiaryHelper.parseEarlierOrLater; - $scope.getEarlierOrLater = DiaryHelper.getEarlierOrLater; - $scope.getLongerOrShorter = DiaryHelper.getLongerOrShorter; - $scope.getIcon = DiaryHelper.getIcon; - $scope.getHumanReadable = DiaryHelper.getHumanReadable; $scope.trip = Timeline.getTrip($stateParams.tripId); - $scope.getKmph = DiaryHelper.getKmph; - $scope.getFormattedDistance = DiaryHelper.getFormattedDistance; - $scope.getSectionDetails = DiaryHelper.getSectionDetails; - $scope.getFormattedTime = DiaryHelper.getFormattedTime; - $scope.getLocalTimeString = DiaryHelper.getLocalTimeString; - $scope.getFormattedTimeRange = DiaryHelper.getFormattedTimeRange; - $scope.getFormattedDuration = DiaryHelper.getFormattedDuration; - $scope.getTripDetails = DiaryHelper.getTripDetails - $scope.tripgj = Timeline.getTripWrapper($stateParams.tripId); + $scope.tripgj = $scope.trip == undefined? {"sections": []} : Timeline.getTripWrapper($stateParams.tripId); $scope.formattedSectionProperties = $scope.tripgj.sections.map(function(s) { return {"fmt_time": DiaryHelper.getLocalTimeString(s.properties.start_local_dt), "fmt_time_range": DiaryHelper.getFormattedTimeRange(s.properties.end_ts, s.properties.start_ts), - "fmt_distance": DiaryHelper.getFormattedDistance(s.properties.distance), + "fmt_distance": ImperialConfig.getFormattedDistance(s.properties.distance), + "fmt_distance_suffix": ImperialConfig.getDistanceSuffix, "icon": DiaryHelper.getIcon(s.properties.sensed_mode), "colorStyle": {color: DiaryHelper.getColor(s.properties.sensed_mode)} }; diff --git a/www/js/diary/infinite_scroll_list.js b/www/js/diary/infinite_scroll_list.js index 7c8b851ec..5956ee443 100644 --- a/www/js/diary/infinite_scroll_list.js +++ b/www/js/diary/infinite_scroll_list.js @@ -12,6 +12,7 @@ angular.module('emission.main.diary.infscrolllist',['ui-leaflet', 'ionic-datepicker', 'emission.main.common.services', 'emission.services', + 'emission.config.imperial', 'emission.survey', 'ng-walkthrough', 'nzTour', 'emission.plugin.kvstore', 'emission.stats.clientstats', @@ -25,7 +26,7 @@ angular.module('emission.main.diary.infscrolllist',['ui-leaflet', $timeout, leafletData, Timeline, CommonGraph, DiaryHelper, SurveyOptions, - Config, PostTripManualMarker, nzTour, KVStore, Logger, UnifiedDataLoader, $ionicPopover, $ionicModal, $translate) { + Config, ImperialConfig, PostTripManualMarker, nzTour, KVStore, Logger, UnifiedDataLoader, $ionicPopover, $ionicModal, $translate) { // TODO: load only a subset of entries instead of everything @@ -306,7 +307,8 @@ angular.module('emission.main.diary.infscrolllist',['ui-leaflet', $scope.populateBasicClasses = function(tripgj) { tripgj.display_start_time = DiaryHelper.getLocalTimeString(tripgj.start_local_dt); tripgj.display_end_time = DiaryHelper.getLocalTimeString(tripgj.end_local_dt); - tripgj.display_distance = DiaryHelper.getFormattedDistance(tripgj.distance); + tripgj.display_distance = ImperialConfig.getFormattedDistance(tripgj.distance); + tripgj.display_distance_suffix = ImperialConfig.getDistanceSuffix; tripgj.display_date = moment(tripgj.start_ts * 1000).format('ddd DD MMM YY'); tripgj.display_time = DiaryHelper.getFormattedTimeRange(tripgj.start_ts, tripgj.end_ts); diff --git a/www/js/diary/list.js b/www/js/diary/list.js index 597cd1e81..80045dbde 100644 --- a/www/js/diary/list.js +++ b/www/js/diary/list.js @@ -12,6 +12,7 @@ angular.module('emission.main.diary.list',['ui-leaflet', 'ionic-datepicker', 'emission.main.common.services', 'emission.services', + 'emission.config.imperial', 'emission.survey', 'ng-walkthrough', 'nzTour', 'emission.plugin.kvstore', 'emission.stats.clientstats', @@ -26,7 +27,7 @@ angular.module('emission.main.diary.list',['ui-leaflet', ionicDatePicker, leafletData, Timeline, CommonGraph, DiaryHelper, SurveyOptions, - Config, PostTripManualMarker, nzTour, KVStore, Logger, UnifiedDataLoader, $ionicPopover, $translate) { + Config, ImperialConfig, PostTripManualMarker, nzTour, KVStore, Logger, UnifiedDataLoader, $ionicPopover, $translate) { console.log("controller DiaryListCtrl called"); $scope.surveyOpt = SurveyOptions.MULTILABEL; ClientStats.addReading(ClientStats.getStatKeys().LABEL_TAB_SWITCH, @@ -160,7 +161,8 @@ angular.module('emission.main.diary.list',['ui-leaflet', $scope.populateBasicClasses = function(tripgj) { tripgj.display_start_time = DiaryHelper.getLocalTimeString(tripgj.data.properties.start_local_dt); tripgj.display_end_time = DiaryHelper.getLocalTimeString(tripgj.data.properties.end_local_dt); - tripgj.display_distance = DiaryHelper.getFormattedDistance(tripgj.data.properties.distance); + tripgj.display_distance = ImperialConfig.getFormattedDistance(tripgj.data.properties.distance); + tripgj.display_distance_suffix = ImperialConfig.getDistanceSuffix; tripgj.display_time = DiaryHelper.getFormattedTimeRange(tripgj.data.properties.start_ts, tripgj.data.properties.end_ts); tripgj.isDraft = DiaryHelper.isDraft(tripgj); diff --git a/www/js/diary/services.js b/www/js/diary/services.js index ba133174a..5673276ba 100644 --- a/www/js/diary/services.js +++ b/www/js/diary/services.js @@ -144,34 +144,6 @@ angular.module('emission.main.diary.services', ['emission.plugin.logger', return background; } - dh.getKmph = function(section) { - var metersPerSec = section.properties.distance / section.properties.duration; - return (metersPerSec * 3.6).toFixed(2); - }; - dh.getFormattedDistance = function(dist_in_meters) { - if (dist_in_meters > 1000) { - return (dist_in_meters/1000).toFixed(0); - } else { - return (dist_in_meters/1000).toFixed(3); - } - } - - dh.getFormattedDistanceInMiles = function(input) { - return (0.621371 * dh.getFormattedDistance(input)).toFixed(1); - } - - dh.getSectionDetails = function(section) { - var startMoment = moment(section.properties.start_ts * 1000); - var endMoment = moment(section.properties.end_ts * 1000); - var retVal = [startMoment.format('LT'), - endMoment.format('LT'), - endMoment.to(startMoment, true), - formatDistance(section.properties.distance), - tokmph(section.properties.distance, section.properties.duration).toFixed(2), - dh.getHumanReadable(section.properties.sensed_mode)]; - return retVal; - }; - dh.getLocalTimeString = function (dt) { //correcting the date of the processed trips knowing that local_dt months are from 1 -> 12 and for the moment function they need to be between 0 -> 11 let mdt = angular.copy(dt) diff --git a/www/templates/diary/detail.html b/www/templates/diary/detail.html index 503cd224c..c64d582ae 100644 --- a/www/templates/diary/detail.html +++ b/www/templates/diary/detail.html @@ -33,7 +33,7 @@
-

{{'.distance'}}

{{tripgj.display_distance}} km
+

{{'.distance'}}

{{tripgj.display_distance}} {{tripgj.display_distance_suffix}}

{{'.time'}}

{{tripgj.display_time}}
@@ -51,7 +51,7 @@
-
{{sectionFmt.fmt_distance}} km
+
{{sectionFmt.fmt_distance}} {{sectionFmt.fmt_distance_suffix}}
diff --git a/www/templates/diary/infinite_scroll_list.html b/www/templates/diary/infinite_scroll_list.html index f172e4d42..283296dfa 100644 --- a/www/templates/diary/infinite_scroll_list.html +++ b/www/templates/diary/infinite_scroll_list.html @@ -56,7 +56,7 @@

{{'diary.scroll-to-load-more' | transla
-
+
diff --git a/www/templates/diary/list.html b/www/templates/diary/list.html index 51085f1af..3a03b74c8 100644 --- a/www/templates/diary/list.html +++ b/www/templates/diary/list.html @@ -52,7 +52,7 @@
From 38271303dc70feab6064459592482d0b68e3ad94 Mon Sep 17 00:00:00 2001 From: Shankari Date: Fri, 15 Oct 2021 11:53:13 -0700 Subject: [PATCH 036/175] Allow users to resize the items This fixes issues in which the labels are partially hidden on some phones, and is a reasonable workaround for the inability to test with multiple phones. We could even consider allowing users to save their perfect height in a local setting later so they don't have to keep changing the settings every time. I tried to do this automatically, but failed with the current UI https://github.com/e-mission/e-mission-docs/issues/679#issuecomment-944420404 --- www/js/diary/infinite_scroll_list.js | 23 +++++++++++++++++ www/js/diary/list.js | 25 +++++++++++++++++++ www/templates/diary/infinite_scroll_list.html | 7 ++++-- www/templates/diary/list.html | 7 ++++-- 4 files changed, 58 insertions(+), 4 deletions(-) diff --git a/www/js/diary/infinite_scroll_list.js b/www/js/diary/infinite_scroll_list.js index 5956ee443..9a0959d44 100644 --- a/www/js/diary/infinite_scroll_list.js +++ b/www/js/diary/infinite_scroll_list.js @@ -31,7 +31,9 @@ angular.module('emission.main.diary.infscrolllist',['ui-leaflet', // TODO: load only a subset of entries instead of everything console.log("controller InfiniteDiaryListCtrl called"); + const DEFAULT_ITEM_HT = 150; $scope.surveyOpt = SurveyOptions.MULTILABEL; + $scope.itemHt = DEFAULT_ITEM_HT; // Add option const placeLimiter = new Bottleneck({ maxConcurrent: 2, minTime: 500 }); @@ -138,6 +140,7 @@ angular.module('emission.main.diary.infscrolllist',['ui-leaflet', $scope.setupInfScroll = function() { Logger.log("Setting up the scrolling"); + $scope.itemHt = DEFAULT_ITEM_HT; $scope.infScrollControl.reachedEnd = false; $scope.data.allTrips = []; $scope.data.displayTrips = []; @@ -434,6 +437,26 @@ angular.module('emission.main.diary.infscrolllist',['ui-leaflet', }); }; + $scope.increaseHeight = function () { + // let's increase by a small amount to workaround the issue with the + // card not resizing the first time + $scope.itemHt = $scope.itemHt + 5; + const oldDisplayTrips = $scope.data.displayTrips; + const TEN_MS = 10; + $scope.data.displayTrips = []; + $timeout(() => { + $scope.$apply(() => { + // make sure that the new item-height is calculated by resetting the list + // that we iterate over + $scope.data.displayTrips = oldDisplayTrips; + // make sure that the cards within the items are set to the new + // size. Apparently, `ng-style` is not recalulated although the + // variable has changed and the items have changed. + $(".list-card").css("height", $scope.itemHt + "px"); + }); + }, TEN_MS); + }; + /* * Checks if it is the first time the user has loaded the new label tab. If it is then * show a walkthrough and store the info that the user has seen the tutorial. diff --git a/www/js/diary/list.js b/www/js/diary/list.js index 80045dbde..47f4fe0e8 100644 --- a/www/js/diary/list.js +++ b/www/js/diary/list.js @@ -24,22 +24,26 @@ angular.module('emission.main.diary.list',['ui-leaflet', $ionicScrollDelegate, $ionicPopup, ClientStats, $ionicLoading, $ionicActionSheet, + $timeout, ionicDatePicker, leafletData, Timeline, CommonGraph, DiaryHelper, SurveyOptions, Config, ImperialConfig, PostTripManualMarker, nzTour, KVStore, Logger, UnifiedDataLoader, $ionicPopover, $translate) { console.log("controller DiaryListCtrl called"); + const DEFAULT_ITEM_HT = 335; $scope.surveyOpt = SurveyOptions.MULTILABEL; ClientStats.addReading(ClientStats.getStatKeys().LABEL_TAB_SWITCH, {"source": null, "dest": $scope.data? $scope.data.currDay : undefined}); // Add option $scope.labelPopulateFactory = $injector.get($scope.surveyOpt.service); + $scope.itemHt = DEFAULT_ITEM_HT; var readAndUpdateForDay = function(day) { // This just launches the update. The update can complete in the background // based on the time when the database finishes reading. // TODO: Convert the usercache calls into promises so that we don't have to // do this juggling + $scope.itemHt = DEFAULT_ITEM_HT; Timeline.updateForDay(day); // This will be used to show the date of datePicker in the user language. $scope.currDay = moment(day).format('LL'); @@ -338,6 +342,27 @@ angular.module('emission.main.diary.list',['ui-leaflet', }); }; + $scope.increaseHeight = function () { + // let's increase by a small amount to workaround the issue with the + // card not resizing the first time + $scope.itemHt = $scope.itemHt + 5; + const oldDisplayTrips = $scope.data.currDayTripWrappers; + const TEN_MS = 10; + $scope.data.currDayTripWrappers = []; + $timeout(() => { + $scope.$apply(() => { + // make sure that the new item-height is calculated by resetting the list + // that we iterate over + $scope.data.currDayTripWrappers = oldDisplayTrips; + // make sure that the cards within the items are set to the new + // size. Apparently, `ng-style` is not recalulated although the + // variable has changed and the items have changed. + $(".list-card").css("height", $scope.itemHt + "px"); + }); + }, TEN_MS); + }; + + /* * Checks if it is the first time the user has loaded the diary tab. If it is then * show a walkthrough and store the info that the user has seen the tutorial. diff --git a/www/templates/diary/infinite_scroll_list.html b/www/templates/diary/infinite_scroll_list.html index 283296dfa..c9ca18f21 100644 --- a/www/templates/diary/infinite_scroll_list.html +++ b/www/templates/diary/infinite_scroll_list.html @@ -14,6 +14,9 @@ + @@ -49,12 +52,12 @@

{{'diary.scroll-to-load-more' | transla If you want to change this from collection-repeat to ng-repeat, you MUST test on android first to make sure that the scrolling works. --> -
+
{{trip.display_start_time}}
-
+
diff --git a/www/templates/diary/list.html b/www/templates/diary/list.html index 3a03b74c8..4d54ed60e 100644 --- a/www/templates/diary/list.html +++ b/www/templates/diary/list.html @@ -2,6 +2,9 @@ + @@ -36,7 +39,7 @@ MUST test on android first to make sure that the scrolling works. --> -
+
{{tripgj.display_start_time}}
@@ -46,7 +49,7 @@
-
+
From a9334105586b1ca03688fd42152659ca6ee1b10c Mon Sep 17 00:00:00 2001 From: Shankari Date: Fri, 15 Oct 2021 12:16:07 -0700 Subject: [PATCH 037/175] Remove % height for the leaflet map on android as well To see if it fixes https://github.com/e-mission/e-mission-docs/issues/679#issuecomment-944559500 It is already a fixed height on iOS because otherwise it doesn't work https://github.com/e-mission/e-mission-phone/commit/089797efa101cbb639a920869766d3b232c1daa3 --- www/templates/diary/trip-detail-popover.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/www/templates/diary/trip-detail-popover.html b/www/templates/diary/trip-detail-popover.html index 992a202e5..a9071656e 100644 --- a/www/templates/diary/trip-detail-popover.html +++ b/www/templates/diary/trip-detail-popover.html @@ -35,7 +35,7 @@

{{currgj.display_date}}<

From 75c13573758c775c353273d9f4a99283006593ea Mon Sep 17 00:00:00 2001 From: Jack Sullivan Date: Thu, 1 Mar 2018 22:43:42 -0800 Subject: [PATCH 038/175] instrumentation for time spent --- www/js/diary/detail.js | 32 +++++++++++++++++-- www/js/diary/list.js | 5 ++- www/js/metrics.js | 63 ++++++++++++++++++++++++++++++++++++- www/js/stats/clientstats.js | 3 +- 4 files changed, 95 insertions(+), 8 deletions(-) diff --git a/www/js/diary/detail.js b/www/js/diary/detail.js index b75c121c8..1c447d0c9 100644 --- a/www/js/diary/detail.js +++ b/www/js/diary/detail.js @@ -4,9 +4,10 @@ angular.module('emission.main.diary.detail',['ui-leaflet', 'ng-walkthrough', 'emission.services', 'emission.config.imperial', 'emission.plugin.logger', + 'emission.stats.clientstats', 'emission.incident.posttrip.manual']) -.controller("DiaryDetailCtrl", function($scope, $rootScope, $window, $stateParams, $ionicActionSheet, +.controller("DiaryDetailCtrl", function($scope, $rootScope, $window, $stateParams, ClientStats, $ionicActionSheet, leafletData, leafletMapEvents, nzTour, KVStore, Logger, Timeline, DiaryHelper, Config, ImperialConfig, CommHelper, PostTripManualMarker, $translate) { @@ -150,11 +151,38 @@ angular.module('emission.main.diary.detail',['ui-leaflet', 'ng-walkthrough', } $scope.$on('$ionicView.afterEnter', function(ev) { - // Workaround from + // Workaround from // https://github.com/driftyco/ionic/issues/3433#issuecomment-195775629 if(ev.targetScope !== $scope) return; checkDetailTutorialDone(); }); + + $scope.$on('$ionicView.enter',function(){ + $scope.startTime = moment().utc() + ClientStats.addEvent(ClientStats.getStatKeys().EXPANDED_TRIP).then( + function() { + console.log("Added "+ClientStats.getStatKeys().EXPANDED_TRIP+" event"); + } + ); + }); + + $scope.$on('$ionicView.leave',function() { + var timeOnPage = moment().utc() - $scope.startTime; + ClientStats.addReading(ClientStats.getStatKeys().DIARY_TIME, timeOnPage); + }); + + $ionicPlatform.on("pause", function() { + if ($state.$current == "root.main.diary.detail") { + var timeOnPage = moment().utc() - $scope.startTime; + ClientStats.addReading(ClientStats.getStatKeys().DIARY_TIME, timeOnPage); + } + }) + + $ionicPlatform.on("resume", function() { + if ($state.$current == "root.main.diary.detail") { + $scope.startTime = moment().utc() + } + }) /* END: ng-walkthrough code */ }) diff --git a/www/js/diary/list.js b/www/js/diary/list.js index 47f4fe0e8..766d74a94 100644 --- a/www/js/diary/list.js +++ b/www/js/diary/list.js @@ -410,7 +410,7 @@ angular.module('emission.main.diary.list',['ui-leaflet', $scope.checkTripState = function() { window.cordova.plugins.BEMDataCollection.getState().then(function(result) { Logger.log("Current trip state" + JSON.stringify(result)); - if(JSON.stringify(result) == "\"STATE_ONGOING_TRIP\"" || + if(JSON.stringify(result) == "\"STATE_ONGOING_TRIP\"" || JSON.stringify(result) == "\"local.state.ongoing_trip\"") { in_trip = true; } else { @@ -422,7 +422,7 @@ angular.module('emission.main.diary.list',['ui-leaflet', // storing boolean to in_trip and return it in inTrip function // work because ng-show is watching the inTrip function. // Returning a promise to ng-show did not work. - // Changing in_trip = bool value; in checkTripState function + // Changing in_trip = bool value; in checkTripState function // to return bool value and using checkTripState function in ng-show // did not work. $scope.inTrip = function() { @@ -465,7 +465,6 @@ angular.module('emission.main.diary.list',['ui-leaflet', $scope.startTime = moment().utc() } }) - $scope.$on('$ionicView.afterEnter', function() { ClientStats.addEvent(ClientStats.getStatKeys().CHECKED_DIARY).then(function() { diff --git a/www/js/metrics.js b/www/js/metrics.js index 1f2f385fa..18331da18 100644 --- a/www/js/metrics.js +++ b/www/js/metrics.js @@ -4,11 +4,12 @@ angular.module('emission.main.metrics',['nvd3', 'emission.services', 'ionic-datepicker', 'emission.main.metrics.factory', + 'emission.stats.clientstats', 'emission.plugin.kvstore', 'emission.plugin.logger']) .controller('MetricsCtrl', function($scope, $ionicActionSheet, $ionicLoading, - CommHelper, $window, $ionicPopup, + ClientStats, CommHelper, $window, $ionicPopup, ionicDatePicker, $ionicPlatform, FootprintHelper, CalorieCal, $ionicModal, $timeout, KVStore, CarbonDatasetHelper, $rootScope, $location, $state, ReferHelper, Logger, @@ -1067,6 +1068,66 @@ angular.module('emission.main.metrics',['nvd3', getMetrics(); } + $scope.$on('$ionicView.enter',function(){ + $scope.startTime = moment().utc() + ClientStats.addEvent(ClientStats.getStatKeys().OPENED_APP).then( + function() { + console.log("Added "+ClientStats.getStatKeys().OPENED_APP+" event"); + }); + }); + + $scope.$on('$ionicView.leave',function() { + var timeOnPage = moment().utc() - $scope.startTime; + ClientStats.addReading(ClientStats.getStatKeys().DIARY_TIME, timeOnPage); + }); + + $ionicPlatform.on("pause", function() { + if ($state.$current == "root.main.metrics") { + var timeOnPage = moment().utc() - $scope.startTime; + ClientStats.addReading(ClientStats.getStatKeys().DIARY_TIME, timeOnPage); + } + }) + + $ionicPlatform.on("resume", function() { + if ($state.$current == "root.main.metrics") { + $scope.startTime = moment().utc() + } + }) + + $scope.linkToMaps = function() { + let start = $scope.suggestionData.startCoordinates[1] + ',' + $scope.suggestionData.startCoordinates[0]; + let destination = $scope.suggestionData.endCoordinates[1] + ',' + $scope.suggestionData.endCoordinates[0]; + var mode = $scope.suggestionData.mode + if(ionic.Platform.isIOS()){ + if (mode === 'bike') { + mode = 'b'; + } else if (mode === 'public') { + mode = 'r'; + } else if (mode === 'walk') { + mode = 'w'; + } + window.open('https://www.maps.apple.com/?saddr=' + start + '&daddr=' + destination + '&dirflg=' + mode, '_system'); + } else { + if (mode === 'bike') { + mode = 'b'; + } else if (mode === 'public') { + mode = 'r'; + } else if (mode === 'walk') { + mode = 'w'; + } + window.open('https://www.google.com/maps?saddr=' + start + '&daddr=' + destination +'&dirflg=' + mode, '_system'); + } + } + + $scope.linkToDiary = function(trip_id) { + console.log("Loading trip "+trip_id); + window.location.href = "#/root/main/diary/" + trip_id; + } + + $scope.hasUsername = function(obj) { + return (obj.hasOwnProperty('username')); + } + $scope.modeIcon = function(key) { var icons = {"BICYCLING":"ion-android-bicycle", "ON_FOOT":" ion-android-walk", diff --git a/www/js/stats/clientstats.js b/www/js/stats/clientstats.js index 084b12ad2..27ba23962 100644 --- a/www/js/stats/clientstats.js +++ b/www/js/stats/clientstats.js @@ -4,7 +4,7 @@ angular.module('emission.stats.clientstats', []) .factory('ClientStats', function($window) { var clientStat = {}; - + clientStat.CLIENT_TIME = "stats/client_time"; clientStat.CLIENT_ERROR = "stats/client_error"; clientStat.CLIENT_NAV_EVENT = "stats/client_nav_event"; @@ -85,4 +85,3 @@ angular.module('emission.stats.clientstats', []) return clientStat; }) - From e244a99c73ee4793727cb7dcbe07c93748808b84 Mon Sep 17 00:00:00 2001 From: Shankari Date: Fri, 15 Oct 2021 17:40:19 -0700 Subject: [PATCH 039/175] Fix clientstats imports Remove import from the filters since we don't generate stats there Add import to the survey launch since we now do generate stats there Testing done: - verified that there are no errors on the label screen --- www/js/survey/external/launch.js | 2 +- www/js/survey/multilabel/infinite_scroll_filters.js | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/www/js/survey/external/launch.js b/www/js/survey/external/launch.js index 1ea4c44c9..3c6cea1c5 100644 --- a/www/js/survey/external/launch.js +++ b/www/js/survey/external/launch.js @@ -4,7 +4,7 @@ angular.module('emission.survey.external.launch', ['emission.services', 'emission.plugin.logger', 'emission.stats.clientstats']) -.factory('SurveyLaunch', function($http, $window, $ionicPopup, $rootScope, +.factory('SurveyLaunch', function($http, $window, $ionicPopup, $rootScope, ClientStats, CommHelper, Logger) { var surveylaunch = {}; diff --git a/www/js/survey/multilabel/infinite_scroll_filters.js b/www/js/survey/multilabel/infinite_scroll_filters.js index 340542b83..ea9de3ed1 100644 --- a/www/js/survey/multilabel/infinite_scroll_filters.js +++ b/www/js/survey/multilabel/infinite_scroll_filters.js @@ -10,10 +10,9 @@ angular.module('emission.survey.multilabel.infscrollfilters',[ 'emission.survey.multilabel.services', - 'emission.stats.clientstats', 'emission.plugin.logger' ]) -.factory('InfScrollFilters', function(Logger, ConfirmHelper, ClientStats, $translate){ +.factory('InfScrollFilters', function(Logger, ConfirmHelper, $translate){ var sf = {}; var unlabeledCheck = function(t) { return ConfirmHelper.INPUTS From 5decf90d89fa55921a1caf3776b4099011bb5780 Mon Sep 17 00:00:00 2001 From: Shankari Date: Fri, 15 Oct 2021 22:44:39 -0700 Subject: [PATCH 040/175] Support live-reload of the diary screen - Return an "undefined" trip/trip wrapper if we are live reloading and don't have the timeline maps populated - we could also choose to check for the existence of the maps directly, but this implementation also fixes the case in which the map exists but the trip doesn't exist in the map - Skip the `$scope` instantiation code if the trip is undefined - Return to the main list in this case, since otherwise we have a blank detail screen --- www/js/diary/detail.js | 10 ++++++++-- www/js/diary/services.js | 4 ++-- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/www/js/diary/detail.js b/www/js/diary/detail.js index 1c447d0c9..efcd6bf67 100644 --- a/www/js/diary/detail.js +++ b/www/js/diary/detail.js @@ -7,7 +7,8 @@ angular.module('emission.main.diary.detail',['ui-leaflet', 'ng-walkthrough', 'emission.stats.clientstats', 'emission.incident.posttrip.manual']) -.controller("DiaryDetailCtrl", function($scope, $rootScope, $window, $stateParams, ClientStats, $ionicActionSheet, +.controller("DiaryDetailCtrl", function($scope, $rootScope, $window, $ionicPlatform, + $state, $stateParams, ClientStats, $ionicActionSheet, leafletData, leafletMapEvents, nzTour, KVStore, Logger, Timeline, DiaryHelper, Config, ImperialConfig, CommHelper, PostTripManualMarker, $translate) { @@ -63,7 +64,11 @@ angular.module('emission.main.diary.detail',['ui-leaflet', 'ng-walkthrough', }; }); - console.log("trip.start_place = " + JSON.stringify($scope.trip.start_place)); + if (!angular.isDefined($scope.trip) || !angular.isDefined($scope.tripgj)) { + console.log("Detail trip not defined, going back to the list view") + $state.go("root.main.diary"); + } else { + console.log("trip.start_place = " , $scope.trip); var data = []; var start_ts = $scope.trip.properties.start_ts; @@ -103,6 +108,7 @@ angular.module('emission.main.diary.detail',['ui-leaflet', 'ng-walkthrough', //Update the chart when window resizes. nv.utils.windowResize(chart.update); nv.addGraph(chart); + } /* START: ng-walkthrough code */ // Tour steps diff --git a/www/js/diary/services.js b/www/js/diary/services.js index 5673276ba..e3d30e62f 100644 --- a/www/js/diary/services.js +++ b/www/js/diary/services.js @@ -1166,11 +1166,11 @@ angular.module('emission.main.diary.services', ['emission.plugin.logger', } timeline.getTrip = function(tripId) { - return timeline.data.tripMap[tripId]; + return angular.isDefined(timeline.data.tripMap)? timeline.data.tripMap[tripId] : undefined; }; timeline.getTripWrapper = function(tripId) { - return timeline.data.tripWrapperMap[tripId]; + return angular.isDefined(timeline.data.tripWrapperMap)? timeline.data.tripWrapperMap[tripId] : undefined; }; /* From cb98fb1aa93cf2a43cad124d15505032e74ffe10 Mon Sep 17 00:00:00 2001 From: Shankari Date: Sat, 16 Oct 2021 06:37:45 -0700 Subject: [PATCH 041/175] Fill in new confirmed_trip fields into the unprocessed trips as well MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In https://github.com/shankari/e-mission-server/commit/78a3ebb612077bea923d922e6cdfbca4ccfa1921 we changed the geojson export code to add in other confirmed trip fields - user inputs, inferred labels, etc Then, as part of https://github.com/e-mission/e-mission-phone/commit/d9cc13bbc38197f6577044a911ef2e68f9b86519 we copied these over, so that the inference code would Just Work. In this commit, we add empty top-level versions of these fields for unprocessed trips as well. Without this change, we sometimes get an error in `www/js/survey/multilabel/multi-label-ui.js` ``` 274 if (!angular.isDefined(userInputLabel)) { 275 userInputLabel = trip.user_input[mls.inputType2retKey(inputType)]; 276 } ``` because `user_input` is undefined Testing done: without the change: user_input is defined for processed trips ``` For checking user_input, trip starting at 2016-08-04T16:34:45.744782-10:00 is {"mode_confirm":"walk","purpose_confirm":"airporttransfer"} ``` but not for unprocessed trips ``` For checking user_input, trip starting at 2016-08-05T04:55:09-07:00 is undefined while populating trips, user_input not found distance: 3408.6004334046456 duration: 1022.720999956131 end_fmt_time: "2016-08-05T05:12:12-07:00" end_loc: {type: "Point", coordinates: Array(2)} end_local_dt: {timezone: undefined, year: 2016, month: 8, day: 5, weekday: 5, …} end_place: {$oid: "unprocessed_1470399132.638"} end_ts: 1470399132.638 feature_type: "trip" raw_trip: [] sensed_mode: "MotionTypes.UNPROCESSED" source: "unprocessed" start_fmt_time: "2016-08-05T04:55:09-07:00" start_loc: {type: "Point", coordinates: Array(2)} start_local_dt: {timezone: undefined, year: 2016, month: 8, day: 5, weekday: 5, …} start_place: {$oid: "unprocessed_1470398109.917"} start_ts: 1470398109.917 trip_id: {$oid: "unprocessed_1470398109.917_1470399132.638"} __proto__: Object ``` with the change, we don't get the "is undefined" log statement for any trips --- www/js/diary/list.js | 3 +++ www/js/diary/services.js | 8 ++++++++ 2 files changed, 11 insertions(+) diff --git a/www/js/diary/list.js b/www/js/diary/list.js index 766d74a94..474da7cb5 100644 --- a/www/js/diary/list.js +++ b/www/js/diary/list.js @@ -223,6 +223,9 @@ angular.module('emission.main.diary.list',['ui-leaflet', tripgj.end_ts = tripgj.data.properties.end_ts; tripgj.inferred_labels = tripgj.data.properties.inferred_labels; tripgj.user_input = tripgj.data.properties.user_input; + if (tripgj.user_input == undefined) { + console.log("while populating trips, user_input not found", tripgj.data.properties); + } $scope.labelPopulateFactory.populateInputsAndInferences(tripgj, $scope.data.unifiedConfirmsResults); $scope.populateCommonInfo(tripgj); }); diff --git a/www/js/diary/services.js b/www/js/diary/services.js index e3d30e62f..c37f80d7b 100644 --- a/www/js/diary/services.js +++ b/www/js/diary/services.js @@ -817,6 +817,10 @@ angular.module('emission.main.diary.services', ['emission.plugin.logger', start_local_dt: moment2localdate(startMoment), start_ts: startPoint.data.ts, times: times, + inferred_labels: [], + expectation: 0, + confidence_threshold: 0, + user_input: {}, trip_id: {$oid: tripAndSectionId} } } @@ -939,6 +943,10 @@ angular.module('emission.main.diary.services', ['emission.plugin.logger', id: section_gj.features[0].id, type: "FeatureCollection", features: features, + inferred_labels: [], + expectation: 0, + confidence_threshold: 0, + user_input: {}, properties: angular.copy(section_gj.features[0].properties) } From 1634c5f76ec228bf21c9051aee9a00d51c1dce27 Mon Sep 17 00:00:00 2001 From: Shankari Date: Sat, 16 Oct 2021 10:36:26 -0700 Subject: [PATCH 042/175] Fix minor issues with refactoring of retrieval code MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The retrieval code was refactored for greater performance https://github.com/e-mission/e-mission-phone/commit/f3ea875f28fd865d6c740d5c14929e50b2eb693b However, this introduced some minor regressions. https://github.com/e-mission/e-mission-docs/issues/679#issuecomment-944929186 which were caused due to incorrect parameter passing and resulting "undefined" values. https://github.com/e-mission/e-mission-docs/issues/679#issuecomment-944957477 Testing done: while reading data for 4th August ---- we detect that the pipeline has finished running ``` INFO:Selected date is :1470294000000 getting pipeline complete timestamp DEBUG:complete_ts = 1470951950.271(Thu Aug 11 2016 14:45:50 GMT-0700) end of current day = 1470380399(Thu Aug 04 2016 23:59:59 GMT-0700) retVal = true Returning 1470951950.271,true ``` we only read entries after `1470951950.271 = 2016-08-11T21:45:50.271000+00:00` ``` getRawEntries: about to get pushGetJSON for the timestamp About to return message {"key_list":["manual/mode_confirm"],"start_time":1470951950.271,"end_time":1634403476,"key_time":"metadata.write_ts"} getRawEntries: about to get pushGetJSON for the timestamp About to return message {"key_list":["manual/purpose_confirm"],"start_time":1470951950.271,"end_time":1634403476,"key_time":"metadata.write_ts"} ``` we got a fair number of unprocessed inputs, mainly because we only filled in the inputs way after the pipeline ``` About to show 'Reading from server' DEBUG:About to dedup localResult = 0remoteResult = 52 DEBUG:Deduped list = 52 DEBUG:About to dedup localResult = 0remoteResult = 55 DEBUG:Deduped list = 55 unprocessed manual inputs 52 MODE, 55 PURPOSE ``` And we only processed trips from the 4th. ``` DEBUG:while reading data for 1470294000000 from server, got nTrips = 9 About to hide 'Reading from server' Finished hiding ionicLoading, returning list of size 9 Reading trips from server finished successfully with length 9 completeStatus = true trip count = 9, calling processTripsForDay About to show 'Processing trips' 0:2016-08-04T10:03:51.235000-10:00, 1880.7650001049042 1:2016-08-04T10:41:32.136385-10:00, 8056.584614753723 2:2016-08-04T13:10:38.739684-10:00, 605.260315656662 3:2016-08-04T13:40:36.959000-10:00, 135.75 4:2016-08-04T13:46:26.561801-10:00, 745.4381992816925 5:2016-08-04T14:06:52.592000-10:00, 280.5680000782013 6:2016-08-04T14:18:35.840464-10:00, 936.7305357456207 7:2016-08-04T14:39:38.288795-10:00, 5956.420205116272 8:2016-08-04T16:34:45.744782-10:00, 232.60321807861328 Processing trip starting at 2016-08-04T13:10:38.739684-10:00 {data: {…}, start_place: {…}, style: ƒ, onEachFeature: ƒ, pointToLayer: ƒ, …} Processing trip starting at 2016-08-04T13:40:36.959000-10:00 {data: {…}, start_place: {…}, style: ƒ, onEachFeature: ƒ, pointToLayer: ƒ, …} Processing trip starting at 2016-08-04T13:46:26.561801-10:00 {data: {…}, start_place: {…}, style: ƒ, onEachFeature: ƒ, pointToLayer: ƒ, …} Processing trip starting at 2016-08-04T14:06:52.592000-10:00 {data: {…}, start_place: {…}, style: ƒ, onEachFeature: ƒ, pointToLayer: ƒ, …} Processing trip starting at 2016-08-04T14:18:35.840464-10:00 {data: {…}, start_place: {…}, style: ƒ, onEachFeature: ƒ, pointToLayer: ƒ, …} Processing trip starting at 2016-08-04T14:39:38.288795-10:00 {data: {…}, start_place: {…}, style: ƒ, onEachFeature: ƒ, pointToLayer: ƒ, …} Processing trip starting at 2016-08-04T16:34:45.744782-10:00 {data: {…}, start_place: {…}, style: ƒ, onEachFeature: ƒ, pointToLayer: ƒ, …} About to hide 'Processing trips' ``` --- www/js/diary/services.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/www/js/diary/services.js b/www/js/diary/services.js index c37f80d7b..006649ddd 100644 --- a/www/js/diary/services.js +++ b/www/js/diary/services.js @@ -610,7 +610,7 @@ angular.module('emission.main.diary.services', ['emission.plugin.logger', +" end of current day = " +eod+"("+moment.unix(eod).toString()+")" +" retVal = "+retVal); - return retVal; + return [result.complete_ts, retVal]; }); } @@ -1130,7 +1130,7 @@ angular.module('emission.main.diary.services', ['emission.plugin.logger', let allTripsPromise = tripsReadPromise.then((processedTripList) => { console.log("Reading trips from server finished successfully with length " +processedTripList.length+" completeStatus = "+completeStatus); - return addUnprocessedTrips(processedTripList, completeStatus); + return addUnprocessedTrips(processedTripList, day, completeStatus); }).then((combinedTripList) => processOrDisplayNone(day, combinedTripList)); return Promise.all([allManualPromise, allTripsPromise]).then(() => { console.log("Finished reading processed/unprocessed trips with length " @@ -1144,7 +1144,7 @@ angular.module('emission.main.diary.services', ['emission.plugin.logger', var isProcessingCompletePromise = timeline.isProcessingComplete(day); // First get the pipeline complete timestamp - isProcessingCompletePromise.then((completeTs, completeStatus) => { + isProcessingCompletePromise.then(([completeTs, completeStatus]) => { // then, in parallel, read unprocessed user inputs // and trips // Also mode/purpose and (currently disabled) survey answers From 61d8690adb3adc2c569229b3379e0981b95fdcae Mon Sep 17 00:00:00 2001 From: Shankari Date: Sat, 16 Oct 2021 10:59:08 -0700 Subject: [PATCH 043/175] Metrics screen should have metrics, not diary stats --- www/js/metrics.js | 4 ++-- www/js/stats/clientstats.js | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/www/js/metrics.js b/www/js/metrics.js index 18331da18..a1ca629b6 100644 --- a/www/js/metrics.js +++ b/www/js/metrics.js @@ -1078,13 +1078,13 @@ angular.module('emission.main.metrics',['nvd3', $scope.$on('$ionicView.leave',function() { var timeOnPage = moment().utc() - $scope.startTime; - ClientStats.addReading(ClientStats.getStatKeys().DIARY_TIME, timeOnPage); + ClientStats.addReading(ClientStats.getStatKeys().METRICS_TIME, timeOnPage); }); $ionicPlatform.on("pause", function() { if ($state.$current == "root.main.metrics") { var timeOnPage = moment().utc() - $scope.startTime; - ClientStats.addReading(ClientStats.getStatKeys().DIARY_TIME, timeOnPage); + ClientStats.addReading(ClientStats.getStatKeys().METRICS_TIME, timeOnPage); } }) diff --git a/www/js/stats/clientstats.js b/www/js/stats/clientstats.js index 27ba23962..9d76964ad 100644 --- a/www/js/stats/clientstats.js +++ b/www/js/stats/clientstats.js @@ -15,6 +15,7 @@ angular.module('emission.stats.clientstats', []) BUTTON_FORCE_SYNC: "button_sync_forced", CHECKED_DIARY: "checked_diary", DIARY_TIME: "diary_time", + METRICS_TIME: "diary_time", CHECKED_INF_SCROLL: "checked_inf_scroll", INF_SCROLL_TIME: "inf_scroll_time", VERIFY_TRIP: "verify_trip", From 06295b27cac920e632ab6730a6c6e5b1a18495ce Mon Sep 17 00:00:00 2001 From: Shankari Date: Sat, 16 Oct 2021 11:07:51 -0700 Subject: [PATCH 044/175] Fix name --- www/js/stats/clientstats.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/www/js/stats/clientstats.js b/www/js/stats/clientstats.js index 9d76964ad..3053b0282 100644 --- a/www/js/stats/clientstats.js +++ b/www/js/stats/clientstats.js @@ -15,7 +15,7 @@ angular.module('emission.stats.clientstats', []) BUTTON_FORCE_SYNC: "button_sync_forced", CHECKED_DIARY: "checked_diary", DIARY_TIME: "diary_time", - METRICS_TIME: "diary_time", + METRICS_TIME: "metrics_time", CHECKED_INF_SCROLL: "checked_inf_scroll", INF_SCROLL_TIME: "inf_scroll_time", VERIFY_TRIP: "verify_trip", From 4c8046f16c00d5e4d93cad963d8af81e319a3968 Mon Sep 17 00:00:00 2001 From: Shankari Date: Mon, 18 Oct 2021 14:03:47 -0700 Subject: [PATCH 045/175] Replace the help/walkthrough button with the resize icon The top bar on the "infinite scroll" screen is already cluttered, and sometimes there are overlaps. Adding one more button introduces overlaps even where we didn't have them before. We should really replace the button-based labels at the top with icons, or convert to a drop-down. https://github.com/e-mission/e-mission-docs/issues/679#issuecomment-946170746 --- www/templates/diary/infinite_scroll_list.html | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/www/templates/diary/infinite_scroll_list.html b/www/templates/diary/infinite_scroll_list.html index c9ca18f21..e90aad4c7 100644 --- a/www/templates/diary/infinite_scroll_list.html +++ b/www/templates/diary/infinite_scroll_list.html @@ -2,7 +2,9 @@ - +
From 6ebeb28b79c2f28638a68b2df15b1ef03fd52311 Mon Sep 17 00:00:00 2001 From: Shankari Date: Mon, 18 Oct 2021 15:35:32 -0700 Subject: [PATCH 046/175] First beta testing version Includes all changes until: https://github.com/e-mission/e-mission-docs/issues/680#issuecomment-945401137 These are primarily: - bump up the version number - bump up the SDK to API 30 - bump up android to 10.1.0 - bump up ios to 6.2.0 - bump up versions of all non-OpenPATH plugins required, including switching to new repo hosts if needed. + add barcode scanner + add badge plugin manully (to get the most recent version and support the new android gradle plugin) - bump up versions of gradle and cocoapods - remove temporary workaround to uninstall tools 31 since we have upgraded to android 10 --- config.cordovabuild.xml | 4 +-- package.cordovabuild.json | 41 ++++++++++++++++------------- setup/export_shared_dep_versions.sh | 12 ++++----- setup/setup_android_native.sh | 5 ---- setup/setup_shared_native.sh | 2 +- 5 files changed, 32 insertions(+), 32 deletions(-) diff --git a/config.cordovabuild.xml b/config.cordovabuild.xml index 2f7670608..e422e89d0 100644 --- a/config.cordovabuild.xml +++ b/config.cordovabuild.xml @@ -1,5 +1,5 @@ - + emission A commute pattern tracker and carbon footprint estimator. @@ -46,7 +46,7 @@ - + diff --git a/package.cordovabuild.json b/package.cordovabuild.json index 9a44d7f92..ee5126dce 100644 --- a/package.cordovabuild.json +++ b/package.cordovabuild.json @@ -1,6 +1,6 @@ { "name": "edu.berkeley.eecs.emission", - "version": "3.0.0", + "version": "3.1.0", "displayName": "emission", "license": "BSD-3-Clause", "repository": { @@ -18,7 +18,7 @@ "ios" ], "plugins": { - "phonegap-plugin-push": { + "@havesource/cordova-plugin-push": { "FCM_VERSION": "17.0.0" }, "cordova-plugin-ionic-keyboard": {}, @@ -26,14 +26,17 @@ "cordova-plugin-file": {}, "cordova-plugin-device": {}, "cordova-plugin-customurlscheme": { - "URL_SCHEME": "emission" + "URL_SCHEME": "emission", + "ANDROID_SCHEME": " ", + "ANDROID_HOST": " ", + "ANDROID_PATHPREFIX": "/" }, "cordova-plugin-email-composer": { "ANDROID_SUPPORT_V4_VERSION": "27.+" }, "cordova-plugin-x-socialsharing": { - "PHOTO_LIBRARY_ADD_USAGE_DESCRIPTION": "This app requires photo library access to function properly.", - "PHOTO_LIBRARY_USAGE_DESCRIPTION": "This app requires photo library access to function properly." + "PHOTO_LIBRARY_ADD_USAGE_DESCRIPTION": "This app requires photo library access to share photos on social media.", + "PHOTO_LIBRARY_USAGE_DESCRIPTION": "This app requires photo library access to share photos on social media." }, "cordova-plugin-inappbrowser": {}, "cordova-plugin-local-notification": {}, @@ -48,7 +51,6 @@ "cordova-plugin-ionic-webview": { "ANDROID_SUPPORT_ANNOTATIONS_VERSION": "27.+" }, - "cordova-plugin-whitelist": {}, "cordova-plugin-em-jwt-auth": { "AUTH_VERSION": "17.0.0" }, @@ -61,17 +63,19 @@ "cordova-plugin-em-transition-notify": {}, "cordova-plugin-em-unifiedlogger": {}, "cordova-plugin-em-usercache": {}, - "cordova-plugin-androidx-adapter": {} + "cordova-plugin-androidx-adapter": {}, + "phonegap-plugin-barcodescanner": {}, + "cordova-plugin-badge": {} } }, "dependencies": { - "cordova-android": "9.0.0", - "cordova-ios": "6.1.0", - "cordova-plugin-advanced-http": "3.0.0", + "cordova-android": "10.1.0", + "cordova-ios": "6.2.0", + "cordova-plugin-advanced-http": "3.2.2", "cordova-plugin-androidx-adapter": "git+https://github.com/dpa99c/cordova-plugin-androidx-adapter.git", - "cordova-plugin-app-version": "0.1.9", - "cordova-plugin-customurlscheme": "5.0.1", - "cordova-plugin-device": "2.0.1", + "cordova-plugin-app-version": "0.1.12", + "cordova-plugin-customurlscheme": "5.0.2", + "cordova-plugin-device": "2.0.3", "cordova-plugin-em-datacollection": "git+https://github.com/e-mission/e-mission-data-collection.git#v1.6.0", "cordova-plugin-em-jwt-auth": "git+https://github.com/e-mission/cordova-jwt-auth.git#v1.6.4", "cordova-plugin-em-server-communication": "git+https://github.com/e-mission/cordova-server-communication.git#v1.2.3", @@ -82,15 +86,16 @@ "cordova-plugin-em-usercache": "git+https://github.com/e-mission/cordova-usercache.git#v1.1.3", "cordova-plugin-email-composer": "0.9.2", "cordova-plugin-file": "6.0.2", - "cordova-plugin-inappbrowser": "4.0.0", - "cordova-plugin-ionic": "5.4.7", + "cordova-plugin-inappbrowser": "5.0.0", + "cordova-plugin-ionic": "5.5.1", "cordova-plugin-ionic-keyboard": "2.2.0", "cordova-plugin-ionic-webview": "5.0.0", "cordova-plugin-local-notification": "0.9.0-beta.3", - "cordova-plugin-whitelist": "~1.3.3", - "cordova-plugin-x-socialsharing": "6.0.0", + "cordova-plugin-x-socialsharing": "6.0.3", "fs-extra": "^9.0.1", "klaw-sync": "^6.0.0", - "phonegap-plugin-push": "=2.3.0" + "phonegap-plugin-barcodescanner": "git+https://github.com/phonegap/phonegap-plugin-barcodescanner#v8.1.0", + "cordova-plugin-badge": "git+https://github.com/katzer/cordova-plugin-badge.git", + "@havesource/cordova-plugin-push": "2.0.0" } } diff --git a/setup/export_shared_dep_versions.sh b/setup/export_shared_dep_versions.sh index 8083d2e37..c96d16537 100644 --- a/setup/export_shared_dep_versions.sh +++ b/setup/export_shared_dep_versions.sh @@ -1,9 +1,9 @@ -export NVM_VERSION=0.36.0 -export NODE_VERSION=14.7.0 -export NPM_VERSION=6.14.8 -export RUBY_VERSION=2.6.0 -export COCOAPODS_VERSION=1.10.0 -export GRADLE_VERSION=6.7 +export NVM_VERSION=0.39.0 +export NODE_VERSION=14.18.1 +export NPM_VERSION=6.14.15 +export RUBY_VERSION=2.6.3 +export COCOAPODS_VERSION=1.11.2 +export GRADLE_VERSION=7.1.1 export NVM_DIR="$HOME/.nvm" export RUBY_PATH=$HOME/.gem/ruby/$RUBY_VERSION/bin diff --git a/setup/setup_android_native.sh b/setup/setup_android_native.sh index 0f5328c5a..5b4ea6a4b 100644 --- a/setup/setup_android_native.sh +++ b/setup/setup_android_native.sh @@ -17,11 +17,6 @@ ANDROID_BUILD_TOOLS_VERSION=27.0.3 MIN_SDK_VERSION=21 TARGET_SDK_VERSION=28 -echo "Uninstalling build tools > 30" -echo "As a temporary workaround until we upgrade to cordova 10" -SDKMANAGER=$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager -echo y | $SDKMANAGER --uninstall "build-tools;31.0.0" - # Setup the development environment source setup/setup_shared.sh diff --git a/setup/setup_shared_native.sh b/setup/setup_shared_native.sh index c421a0a64..40ff7536c 100644 --- a/setup/setup_shared_native.sh +++ b/setup/setup_shared_native.sh @@ -26,7 +26,7 @@ sed -i -e "s|/usr/bin/env node|/usr/bin/env node --unhandled-rejections=strict|" npx cordova prepare -EXPECTED_COUNT=27 +EXPECTED_COUNT=25 INSTALLED_COUNT=`npx cordova plugin list | wc -l` echo "Found $INSTALLED_COUNT plugins, expected $EXPECTED_COUNT" if [ $INSTALLED_COUNT -lt $EXPECTED_COUNT ]; From ce6bccfdb2d24a1a02ab24c6815a6c1e2846299e Mon Sep 17 00:00:00 2001 From: Shankari Date: Mon, 18 Oct 2021 17:30:15 -0700 Subject: [PATCH 047/175] Set the FCM version to 18+ to be consistent with https://github.com/havesource/cordova-plugin-push/issues/83#issuecomment-778780823 This seems to fix the error in https://github.com/e-mission/e-mission-docs/issues/680#issuecomment-946269095 --- package.cordovabuild.json | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/package.cordovabuild.json b/package.cordovabuild.json index ee5126dce..86c43ee8c 100644 --- a/package.cordovabuild.json +++ b/package.cordovabuild.json @@ -19,7 +19,9 @@ ], "plugins": { "@havesource/cordova-plugin-push": { - "FCM_VERSION": "17.0.0" + "ANDROID_SUPPORT_V13_VERSION": "28.0.0", + "FCM_VERSION": "18.+", + "IOS_FIREBASE_MESSAGING_VERSION": "~> 6.32.2" }, "cordova-plugin-ionic-keyboard": {}, "cordova-plugin-app-version": {}, From 7eca45767c0f5c2baaad96f44c3682be2bfa55f7 Mon Sep 17 00:00:00 2001 From: Shankari Date: Thu, 21 Oct 2021 22:44:39 -0700 Subject: [PATCH 048/175] Change the build script to work with aab Instead of the old apk. This is consistent with requirements that all new apps must be built using aab https://github.com/e-mission/e-mission-docs/issues/680#issuecomment-947017212 --- bin/sign_and_align_keys.sh | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/bin/sign_and_align_keys.sh b/bin/sign_and_align_keys.sh index 034b8a63a..3a0bb0d76 100644 --- a/bin/sign_and_align_keys.sh +++ b/bin/sign_and_align_keys.sh @@ -11,6 +11,7 @@ fi # Sign and release the L+ version # Make sure the highest supported version has the biggest version code npx cordova build android --release -- --minSdkVersion=22 -cp platforms/android/app/build/outputs/apk/release/app-release-unsigned.apk platforms/android/app/build/outputs/apk/app-release-signed-unaligned.apk -jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore ../config_files/production.keystore ./platforms/android/app/build/outputs/apk/app-release-signed-unaligned.apk androidproductionkey -~/Library/Android/sdk/build-tools/30.0.1/zipalign -v 4 platforms/android/app/build/outputs/apk/app-release-signed-unaligned.apk $1-build-$2.apk +# cp platforms/android/app/build/outputs/apk/release/app-release-unsigned.aab platforms/android/app/build/outputs/apk/app-release-signed-unaligned.apk +jarsigner -verbose -sigalg SHA256withRSA -digestalg SHA-256 -keystore ../config_files/production.keystore ./platforms/android/app/build/outputs/bundle/release/app-release.aab androidproductionkey +cp platforms/android/app/build/outputs/bundle/release/app-release.aab $1-build-$2.aab +# ~/Library/Android/sdk/build-tools/30.0.1/zipalign -v 4 platforms/android/app/build/outputs/apk/app-release-signed-unaligned.apk $1-build-$2.apk From 352c2ae5e41e8100f34521a50c3f2db054a7655c Mon Sep 17 00:00:00 2001 From: "K. Shankari" Date: Fri, 22 Oct 2021 10:18:22 -0700 Subject: [PATCH 049/175] Remove the hardcoded badge plugin It is still auto-installed as part of the local notification package https://github.com/e-mission/e-mission-docs/issues/680#issuecomment-949821492 --- package.cordovabuild.json | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/package.cordovabuild.json b/package.cordovabuild.json index 86c43ee8c..d968ccabe 100644 --- a/package.cordovabuild.json +++ b/package.cordovabuild.json @@ -66,8 +66,7 @@ "cordova-plugin-em-unifiedlogger": {}, "cordova-plugin-em-usercache": {}, "cordova-plugin-androidx-adapter": {}, - "phonegap-plugin-barcodescanner": {}, - "cordova-plugin-badge": {} + "phonegap-plugin-barcodescanner": {} } }, "dependencies": { @@ -97,7 +96,6 @@ "fs-extra": "^9.0.1", "klaw-sync": "^6.0.0", "phonegap-plugin-barcodescanner": "git+https://github.com/phonegap/phonegap-plugin-barcodescanner#v8.1.0", - "cordova-plugin-badge": "git+https://github.com/katzer/cordova-plugin-badge.git", "@havesource/cordova-plugin-push": "2.0.0" } } From d12485928cef3f26ebd537ebc1bf442d53b7ddd8 Mon Sep 17 00:00:00 2001 From: "K. Shankari" Date: Fri, 22 Oct 2021 10:49:22 -0700 Subject: [PATCH 050/175] Downgrade the ruby version since we don't have a more recent version installed And without this, the RUBY_PATH is incorrect, so cocoapods are not found and the build fails. --- setup/export_shared_dep_versions.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup/export_shared_dep_versions.sh b/setup/export_shared_dep_versions.sh index c96d16537..123580155 100644 --- a/setup/export_shared_dep_versions.sh +++ b/setup/export_shared_dep_versions.sh @@ -1,7 +1,7 @@ export NVM_VERSION=0.39.0 export NODE_VERSION=14.18.1 export NPM_VERSION=6.14.15 -export RUBY_VERSION=2.6.3 +export RUBY_VERSION=2.6.0 export COCOAPODS_VERSION=1.11.2 export GRADLE_VERSION=7.1.1 From 2025e5e0eb046356acf5c4003533ce644127eb5b Mon Sep 17 00:00:00 2001 From: "K. Shankari" Date: Sat, 23 Oct 2021 22:11:13 -0700 Subject: [PATCH 051/175] Upgrade to the updated version of the auth plugin This should fix the pending iOS build error https://github.com/e-mission/e-mission-docs/issues/680#issuecomment-945371010 --- package.cordovabuild.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/package.cordovabuild.json b/package.cordovabuild.json index d968ccabe..257dd6376 100644 --- a/package.cordovabuild.json +++ b/package.cordovabuild.json @@ -54,7 +54,7 @@ "ANDROID_SUPPORT_ANNOTATIONS_VERSION": "27.+" }, "cordova-plugin-em-jwt-auth": { - "AUTH_VERSION": "17.0.0" + "AUTH_VERSION": "19.2.0" }, "cordova-plugin-em-server-communication": {}, "cordova-plugin-em-datacollection": { @@ -78,7 +78,7 @@ "cordova-plugin-customurlscheme": "5.0.2", "cordova-plugin-device": "2.0.3", "cordova-plugin-em-datacollection": "git+https://github.com/e-mission/e-mission-data-collection.git#v1.6.0", - "cordova-plugin-em-jwt-auth": "git+https://github.com/e-mission/cordova-jwt-auth.git#v1.6.4", + "cordova-plugin-em-jwt-auth": "git+https://github.com/e-mission/cordova-jwt-auth.git#v1.6.5", "cordova-plugin-em-server-communication": "git+https://github.com/e-mission/cordova-server-communication.git#v1.2.3", "cordova-plugin-em-serversync": "git+https://github.com/e-mission/cordova-server-sync.git#v1.2.5", "cordova-plugin-em-settings": "git+https://github.com/e-mission/cordova-connection-settings.git#v1.2.2", From 29d2d855acfb7bf91b6bffde1ab8bb94c6fb1a4c Mon Sep 17 00:00:00 2001 From: "K. Shankari" Date: Wed, 27 Oct 2021 13:03:32 -0700 Subject: [PATCH 052/175] Initial version of the status screen (location settings only) Check in the initial version of the long-awaited status screen. - Create a new directive for status checks - Move the `sensor_explanation` code out of the intro file - Change the `sensor_explanation` template to include status checks In the new directive: - create sections for location and fitness (so we can design properly) - create config options for location (settings and permissions) and fitness (permissions) - add explanations of why we need the sensors and what the settings need to be - add status fields for each of the sub-sections and the overall section - provide options to fix issues and to recompute the status - display the error if the fix did not work Testing done: - turned off the location in the settings - refreshed, location settings turned red - fixed, location settings turned green - turned off the location in the settings - refreshed, location settings turned red - tried to fix, but rejected instead of accepted settings - settings stayed red and displayed an error --- www/i18n/en.json | 27 +++ www/index.html | 2 + www/js/appstatus/appstatus.js | 13 ++ www/js/appstatus/permissioncheck.js | 177 +++++++++++++++++++ www/js/intro.js | 40 +---- www/templates/appstatus/permissioncheck.html | 69 ++++++++ www/templates/intro/sensor_explanation.html | 38 +--- 7 files changed, 292 insertions(+), 74 deletions(-) create mode 100644 www/js/appstatus/appstatus.js create mode 100644 www/js/appstatus/permissioncheck.js create mode 100644 www/templates/appstatus/permissioncheck.html diff --git a/www/i18n/en.json b/www/i18n/en.json index 1cb3109d0..0d832dc68 100644 --- a/www/i18n/en.json +++ b/www/i18n/en.json @@ -306,6 +306,33 @@ }, "intro": { + "appstatus": { + "locsettings": { + "name": "Location Settings", + "description": { + "android-lt-9": "Location services should be enabled and set to High Accuracy. This allows us to accurately record the trajectory of the travel", + "android-gte-9": "Location services should be enabled. This allows us to access location data and generate the trip log", + "ios": "Placeholder" + } + }, + "locperms": { + "name": "Location Permissions", + "description": { + "android-lt-6": "Enabled during app installation.", + "android-6-9": "Please select 'allow'", + "android-10": "Please select 'Allow all the time'", + "android-gte-11": "On the app settings page, choose the 'Location' permission and set it to 'Allow all the time'", + "ios": "Placeholder" + } + }, + "fitnessperms": { + "name": "Fitness Permission", + "description": { + "android": "Please allow.", + "ios": "Please allow." + } + } + }, "permissions": { "locationPermExplanation-android-lt-6": "you accepted the permission during installation. You don't need to do anything now.", "locationPermExplanation-android-6-9": "please select 'allow'", diff --git a/www/index.html b/www/index.html index baea9c3e1..1a74b4296 100644 --- a/www/index.html +++ b/www/index.html @@ -9,6 +9,7 @@ + @@ -116,6 +117,7 @@ + diff --git a/www/js/appstatus/appstatus.js b/www/js/appstatus/appstatus.js new file mode 100644 index 000000000..6d55c99a3 --- /dev/null +++ b/www/js/appstatus/appstatus.js @@ -0,0 +1,13 @@ +/* + * Directive to display a set of configurable labels for each trip + * Assumptions: + * - The directive is embedded within an ion-view + * - The controller for the ion-view has a function called + * 'recomputeDisplayTrips` which modifies the trip *list* as necessary. An + * example with the label view is removing the labeled trips from the + * "toLabel" filter. Function can be a no-op (for example, in + * the diary view) + * - The view is associated with a state which we can record in the client stats. + * - The directive implements a `verifyTrip` function that can be invoked by + * other components. + */ diff --git a/www/js/appstatus/permissioncheck.js b/www/js/appstatus/permissioncheck.js new file mode 100644 index 000000000..3f74dd91c --- /dev/null +++ b/www/js/appstatus/permissioncheck.js @@ -0,0 +1,177 @@ +/* + * Directive to enable the permissions required for the app to function properly. + */ + +angular.module('emission.appstatus.permissioncheck', + []) +.directive('permissioncheck', function() { + return { + scope: { + }, + controller: "PermissionCheckControl", + templateUrl: "templates/appstatus/permissioncheck.html" + }; +}). +controller("PermissionCheckControl", function($scope, $element, $attrs, + $ionicPlatform, $ionicPopup, $window, $translate) { + console.log("PermissionCheckControl initialized"); + + $scope.setupLocChecks = function(platform, version) { + if (platform.toLowerCase() == "android") { + return $scope.setupAndroidLocChecks(version); + } else if (platform.toLowerCase() == "ios") { + return $scope.setupIOSLocChecks(version); + } else { + alert("Unknown platform, no tracking"); + } + } + + $scope.setupFitnessChecks = function(platform, version) { + if (platform.toLowerCase() == "android") { + return $scope.setupAndroidFitnessChecks(version); + } else if (platform.toLowerCase() == "ios") { + return $scope.setupIOSFitnessChecks(version); + } else { + alert("Unknown platform, no tracking"); + } + } + + $scope.recomputeLocStatus = function() { + let iconMap = (statusState) => statusState? "✅" : "❌"; + let classMap = (statusState) => statusState? "status-green" : "status-red"; + $scope.locChecks.forEach((lc) => { + lc.statusIcon = iconMap(lc.statusState); + lc.statusClass = classMap(lc.statusState) + }); + $scope.overallLocStatus = $scope.locChecks.map((lc) => lc.statusState).reduce((pv, cv) => pv && cv); + console.log("overallLocStatus = "+$scope.overallLocStatus+" from ", $scope.locChecks); + $scope.overallLocStatusIcon = iconMap($scope.overallLocStatus); + $scope.overallLocStatusClass = classMap($scope.overallLocStatus); + } + + $scope.setupAndroidLocChecks = function(platform, version) { + let checkOrFixSettings = function(nativeFn, showError=true) { + return nativeFn() + .then((status) => { + console.log("availability ", status) + $scope.$apply(() => { + locSettingsCheck.statusState = true; + $scope.recomputeLocStatus(); + }); + return status; + }).catch((error) => { + console.log("Error", error) + if (showError) { + $ionicPopup.alert({ + title: "Error in location settings", + template: "
"+error+"
", + okText: "Please fix again" + }); + }; + $scope.$apply(() => { + locSettingsCheck.statusState = false; + $scope.recomputeLocStatus(); + }); + return error; + }); + } + let fixSettings = function() { + console.log("Fix and refresh location settings"); + return checkOrFixSettings($window.cordova.plugins.BEMDataCollection.fixLocationSettings, showError=true); + }; + let checkSettings = function() { + console.log("Refresh location settings"); + return checkOrFixSettings($window.cordova.plugins.BEMDataCollection.isValidLocationSettings, showError=false); + }; + let fixAndRefreshPermissionsPlaceholder = function() { + console.log("fix or refresh location permissions"); + }; + var androidSettingsDescTag = "intro.appstatus.locsettings.description.android-gte-9"; + if (version < 9) { + androidSettingsDescTag = "intro.appstatus.locsettings.description.android-lt-9"; + } + var androidPermDescTag = "intro.appstatus.locperms.description.android-gte-11"; + if($scope.osver < 6) { + androidPermDescTag = 'intro.appstatus.locperms.description.android-lt-6'; + } else if ($scope.osver < 10) { + androidPermDescTag = "intro.appstatus.locperms.description.android-6-9"; + } else if ($scope.osver < 11) { + androidPermDescTag= "intro.appstatus.locperms.description.android-10"; + } + console.log("description tags are "+androidSettingsDescTag+" "+androidPermDescTag); + // location settings + let locSettingsCheck = { + name: $translate.instant("intro.appstatus.locsettings.name"), + desc: $translate.instant(androidSettingsDescTag), + statusState: false, + fix: fixSettings, + refresh: checkSettings + } + let locPermissionsCheck = { + name: $translate.instant("intro.appstatus.locperms.name"), + desc: $translate.instant(androidPermDescTag), + statusState: false, + fix: fixAndRefreshPermissionsPlaceholder, + refresh: fixAndRefreshPermissionsPlaceholder + } + $scope.locChecks = [locSettingsCheck, locPermissionsCheck]; + let locCheckPromises = $scope.locChecks.map((lc) => lc.refresh()); + console.log(locCheckPromises); + Promise.all(locCheckPromises) + .then((result) => $scope.recomputeLocStatus()) + .catch((error) => $scope.recomputeLocStatus()) + } + + $scope.setupAndroidFitnessChecks = function(platform, version) { + $scope.fitnessPermNeeded = ($scope.osver >= 10); + + let fixAndRefreshPermissionsPlaceholder = function() { + console.log("Fix and refresh fitnessation permissions"); + }; + let fitnessPermissionsCheck = { + name: $translate.instant("intro.appstatus.fitnessperms.name"), + desc: $translate.instant("intro.appstatus.fitnessperms.description.android"), + statusIcon: "✅", + statusClass: "status-green", + fix: fixAndRefreshPermissionsPlaceholder, + refresh: fixAndRefreshPermissionsPlaceholder + } + $scope.fitnessChecks = [fitnessPermissionsCheck]; + $scope.overallFitnessStatusIcon = "✅"; + $scope.overallFitnessStatusClass = "status-green"; + } + + $scope.setupPermissionText = function() { + if($scope.platform.toLowerCase() == "ios") { + if($scope.osver < 13) { + $scope.locationPermExplanation = $translate.instant("intro.permissions.locationPermExplanation-ios-lt-13"); + } else { + $scope.locationPermExplanation = $translate.instant("intro.permissions.locationPermExplanation-ios-gte-13"); + } + } + + $scope.backgroundRestricted = false; + if($window.device.manufacturer.toLowerCase() == "samsung") { + $scope.backgroundRestricted = true; + $scope.allowBackgroundInstructions = $translate.instant("intro.allow_background.samsung"); + } + + console.log("Explanation = "+$scope.locationPermExplanation); + } + + $scope.checkLocationServicesEnabled = function() { + console.log("About to see if location services are enabled"); + } + $ionicPlatform.ready().then(function() { + console.log("app is launched, should refresh"); + $scope.platform = $window.device.platform; + $scope.osver = $window.device.version.split(".")[0]; + $scope.setupPermissionText(); + $scope.setupLocChecks($scope.platform, $scope.osver); + $scope.setupFitnessChecks($scope.platform, $scope.osver); + }); + + $ionicPlatform.on("resume", function() { + console.log("app has resumed, should refresh"); + }); +}); diff --git a/www/js/intro.js b/www/js/intro.js index 5cd3e8fe9..9a8ff4627 100644 --- a/www/js/intro.js +++ b/www/js/intro.js @@ -3,6 +3,7 @@ angular.module('emission.intro', ['emission.splash.startprefs', 'emission.splash.updatecheck', 'emission.survey.external.launch', + 'emission.appstatus.permissioncheck', 'emission.i18n.utils', 'ionic-toast']) @@ -23,42 +24,7 @@ angular.module('emission.intro', ['emission.splash.startprefs', .controller('IntroCtrl', function($scope, $rootScope, $state, $window, $ionicPlatform, $ionicSlideBoxDelegate, - $ionicPopup, $ionicHistory, ionicToast, $timeout, CommHelper, StartPrefs, SurveyLaunch, UpdateCheck, $translate, i18nUtils) { - - $scope.setupPermissionText = function() { - $scope.platform = $window.device.platform; - $scope.osver = $window.device.version.split(".")[0]; - if($scope.platform.toLowerCase() == "android") { - if($scope.osver < 6) { - $scope.locationPermExplanation = $translate.instant('intro.permissions.locationPermExplanation-android-lt-6'); - } else if ($scope.osver < 10) { - $scope.locationPermExplanation = $translate.instant("intro.permissions.locationPermExplanation-android-6-9"); - } else if ($scope.osver < 11) { - $scope.locationPermExplanation = $translate.instant("intro.permissions.locationPermExplanation-android-10"); - } else { - $scope.locationPermExplanation = $translate.instant("intro.permissions.locationPermExplanation-android-gte-11"); - } - } - - if($scope.platform.toLowerCase() == "ios") { - if($scope.osver < 13) { - $scope.locationPermExplanation = $translate.instant("intro.permissions.locationPermExplanation-ios-lt-13"); - } else { - $scope.locationPermExplanation = $translate.instant("intro.permissions.locationPermExplanation-ios-gte-13"); - } - } - - $scope.backgroundRestricted = false; - if($window.device.manufacturer.toLowerCase() == "samsung") { - $scope.backgroundRestricted = true; - $scope.allowBackgroundInstructions = $translate.instant("intro.allow_background.samsung"); - } - - $scope.fitnessPermNeeded = ($scope.platform.toLowerCase() == "ios" || - (($scope.platform.toLowerCase() == "android") && ($scope.osver >= 10))); - - console.log("Explanation = "+$scope.locationPermExplanation); - } + $ionicPopup, $ionicHistory, ionicToast, $timeout, CommHelper, StartPrefs, SurveyLaunch, UpdateCheck, i18nUtils) { var allIntroFiles = Promise.all([ i18nUtils.geti18nFileName("templates/", "intro/summary", ".html"), @@ -184,7 +150,7 @@ angular.module('emission.intro', ['emission.splash.startprefs', } $ionicPlatform.ready().then(function() { - $scope.setupPermissionText(); + console.log("app is launched, currently NOP"); }); }); diff --git a/www/templates/appstatus/permissioncheck.html b/www/templates/appstatus/permissioncheck.html new file mode 100644 index 000000000..12eb19744 --- /dev/null +++ b/www/templates/appstatus/permissioncheck.html @@ -0,0 +1,69 @@ +
+

Location {{overallLocStatusIcon}}

+ +We need this this sensor to read your location data and automatically generate +a trip log that is displayed to you for annotation. We need the background +location permission to track your location in the background, even when the app +is closed. This makes the app easier to use and saves battery since you don't +have to remember to start and stop trip recording. + + +
+
{{locCheck.name}}
+
{{locCheck.statusIcon}}
+
+
{{locCheck.desc}}
+
+ + +
+
+
+
+ +
+
+

Motion and Fitness {{overallFitnessStatusIcon}}

+The fitness sensors distinguish between walking, bicycling and motorized modes. +We use this data in order to separate the parts of multi-modal travel such as +transit. + + +
+
{{fitnessCheck.name}}
+
{{fitnessCheck.statusIcon}}
+
+
{{fitnessCheck.desc}}
+
+ + +
+
+
+
+ + +
+

Notifications

+We need this permission in order to prompt you for your travel mode and purpose. +Please allow. +
+ +
+

Allow background restrictions

+Your phone restricts app operation in the background. This prevents the app +from tracking your location or pushing it to the server. Please enable +background operation for this app with the following instructions: +{{allowBackgroundRestrictions}}. +
+ +
+
+ +
+
+ +
+
+
+ diff --git a/www/templates/intro/sensor_explanation.html b/www/templates/intro/sensor_explanation.html index 08b943769..0cd1ba4fb 100644 --- a/www/templates/intro/sensor_explanation.html +++ b/www/templates/intro/sensor_explanation.html @@ -5,42 +5,6 @@ - - + From ec764686a53a39ae66479d4a0db7b6aaf0862fdc Mon Sep 17 00:00:00 2001 From: "K. Shankari" Date: Wed, 27 Oct 2021 21:52:04 -0700 Subject: [PATCH 053/175] Add status support for the fitness sensors Similar to https://github.com/e-mission/e-mission-phone/pull/804/commits/29d2d855acfb7bf91b6bffde1ab8bb94c6fb1a4c --- www/js/appstatus/permissioncheck.js | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/www/js/appstatus/permissioncheck.js b/www/js/appstatus/permissioncheck.js index 3f74dd91c..11e6659e1 100644 --- a/www/js/appstatus/permissioncheck.js +++ b/www/js/appstatus/permissioncheck.js @@ -50,12 +50,12 @@ controller("PermissionCheckControl", function($scope, $element, $attrs, } $scope.setupAndroidLocChecks = function(platform, version) { - let checkOrFixSettings = function(nativeFn, showError=true) { + let checkOrFix = function(checkObj, nativeFn, showError=true) { return nativeFn() .then((status) => { console.log("availability ", status) $scope.$apply(() => { - locSettingsCheck.statusState = true; + checkObj.statusState = true; $scope.recomputeLocStatus(); }); return status; @@ -69,7 +69,7 @@ controller("PermissionCheckControl", function($scope, $element, $attrs, }); }; $scope.$apply(() => { - locSettingsCheck.statusState = false; + checkObj.statusState = false; $scope.recomputeLocStatus(); }); return error; @@ -77,14 +77,19 @@ controller("PermissionCheckControl", function($scope, $element, $attrs, } let fixSettings = function() { console.log("Fix and refresh location settings"); - return checkOrFixSettings($window.cordova.plugins.BEMDataCollection.fixLocationSettings, showError=true); + return checkOrFix(locSettingsCheck, $window.cordova.plugins.BEMDataCollection.fixLocationSettings, showError=true); }; let checkSettings = function() { console.log("Refresh location settings"); - return checkOrFixSettings($window.cordova.plugins.BEMDataCollection.isValidLocationSettings, showError=false); + return checkOrFix(locSettingsCheck, $window.cordova.plugins.BEMDataCollection.isValidLocationSettings, showError=false); }; - let fixAndRefreshPermissionsPlaceholder = function() { - console.log("fix or refresh location permissions"); + let fixPerms = function() { + console.log("fix and refresh location permissions"); + return checkOrFix(locPermissionsCheck, $window.cordova.plugins.BEMDataCollection.fixLocationPermissions, showError=true); + }; + let checkPerms = function() { + console.log("fix and refresh location permissions"); + return checkOrFix(locPermissionsCheck, $window.cordova.plugins.BEMDataCollection.isValidLocationPermissions, showError=false); }; var androidSettingsDescTag = "intro.appstatus.locsettings.description.android-gte-9"; if (version < 9) { @@ -111,8 +116,8 @@ controller("PermissionCheckControl", function($scope, $element, $attrs, name: $translate.instant("intro.appstatus.locperms.name"), desc: $translate.instant(androidPermDescTag), statusState: false, - fix: fixAndRefreshPermissionsPlaceholder, - refresh: fixAndRefreshPermissionsPlaceholder + fix: fixPerms, + refresh: checkPerms } $scope.locChecks = [locSettingsCheck, locPermissionsCheck]; let locCheckPromises = $scope.locChecks.map((lc) => lc.refresh()); From 7be6cba8b4a4b820df39e01709195f25c4b4a13b Mon Sep 17 00:00:00 2001 From: "K. Shankari" Date: Thu, 28 Oct 2021 09:35:50 -0700 Subject: [PATCH 054/175] Adding in the fitness permission as well --- www/js/appstatus/permissioncheck.js | 104 +++++++++++++++++----------- 1 file changed, 65 insertions(+), 39 deletions(-) diff --git a/www/js/appstatus/permissioncheck.js b/www/js/appstatus/permissioncheck.js index 11e6659e1..ae1fe13db 100644 --- a/www/js/appstatus/permissioncheck.js +++ b/www/js/appstatus/permissioncheck.js @@ -36,9 +36,10 @@ controller("PermissionCheckControl", function($scope, $element, $attrs, } } + let iconMap = (statusState) => statusState? "✅" : "❌"; + let classMap = (statusState) => statusState? "status-green" : "status-red"; + $scope.recomputeLocStatus = function() { - let iconMap = (statusState) => statusState? "✅" : "❌"; - let classMap = (statusState) => statusState? "status-green" : "status-red"; $scope.locChecks.forEach((lc) => { lc.statusIcon = iconMap(lc.statusState); lc.statusClass = classMap(lc.statusState) @@ -49,47 +50,63 @@ controller("PermissionCheckControl", function($scope, $element, $attrs, $scope.overallLocStatusClass = classMap($scope.overallLocStatus); } - $scope.setupAndroidLocChecks = function(platform, version) { - let checkOrFix = function(checkObj, nativeFn, showError=true) { - return nativeFn() - .then((status) => { - console.log("availability ", status) - $scope.$apply(() => { - checkObj.statusState = true; - $scope.recomputeLocStatus(); - }); - return status; - }).catch((error) => { - console.log("Error", error) - if (showError) { - $ionicPopup.alert({ - title: "Error in location settings", - template: "
"+error+"
", - okText: "Please fix again" - }); - }; - $scope.$apply(() => { - checkObj.statusState = false; - $scope.recomputeLocStatus(); + $scope.recomputeFitnessStatus = function() { + $scope.fitnessChecks.forEach((fc) => { + fc.statusIcon = iconMap(fc.statusState); + fc.statusClass = classMap(fc.statusState) + }); + $scope.overallFitnessStatus = $scope.fitnessChecks.map((fc) => fc.statusState).reduce((pv, cv) => pv && cv); + console.log("overallFitnessStatus = "+$scope.overallFitnessStatus+" from ", $scope.fitnessChecks); + $scope.overallFitnessStatusIcon = iconMap($scope.overallFitnessStatus); + $scope.overallFitnessStatusClass = classMap($scope.overallFitnessStatus); + } + + let checkOrFix = function(checkObj, nativeFn, recomputeFn, showError=true) { + return nativeFn() + .then((status) => { + console.log("availability ", status) + $scope.$apply(() => { + checkObj.statusState = true; + recomputeFn(); + }); + return status; + }).catch((error) => { + console.log("Error", error) + if (showError) { + $ionicPopup.alert({ + title: "Error", + template: "
"+error+"
", + okText: "Please fix again" }); - return error; + }; + $scope.$apply(() => { + checkObj.statusState = false; + recomputeFn(); }); - } + return error; + }); + } + + $scope.setupAndroidLocChecks = function(platform, version) { let fixSettings = function() { console.log("Fix and refresh location settings"); - return checkOrFix(locSettingsCheck, $window.cordova.plugins.BEMDataCollection.fixLocationSettings, showError=true); + return checkOrFix(locSettingsCheck, $window.cordova.plugins.BEMDataCollection.fixLocationSettings, + $scope.recomputeLocStatus, showError=true); }; let checkSettings = function() { console.log("Refresh location settings"); - return checkOrFix(locSettingsCheck, $window.cordova.plugins.BEMDataCollection.isValidLocationSettings, showError=false); + return checkOrFix(locSettingsCheck, $window.cordova.plugins.BEMDataCollection.isValidLocationSettings, + $scope.recomputeLocStatus, showError=false); }; let fixPerms = function() { console.log("fix and refresh location permissions"); - return checkOrFix(locPermissionsCheck, $window.cordova.plugins.BEMDataCollection.fixLocationPermissions, showError=true); + return checkOrFix(locPermissionsCheck, $window.cordova.plugins.BEMDataCollection.fixLocationPermissions, + $scope.recomputeLocStatus, showError=true); }; let checkPerms = function() { console.log("fix and refresh location permissions"); - return checkOrFix(locPermissionsCheck, $window.cordova.plugins.BEMDataCollection.isValidLocationPermissions, showError=false); + return checkOrFix(locPermissionsCheck, $window.cordova.plugins.BEMDataCollection.isValidLocationPermissions, + $scope.recomputeLocStatus, showError=false); }; var androidSettingsDescTag = "intro.appstatus.locsettings.description.android-gte-9"; if (version < 9) { @@ -129,21 +146,30 @@ controller("PermissionCheckControl", function($scope, $element, $attrs, $scope.setupAndroidFitnessChecks = function(platform, version) { $scope.fitnessPermNeeded = ($scope.osver >= 10); - - let fixAndRefreshPermissionsPlaceholder = function() { - console.log("Fix and refresh fitnessation permissions"); + + let fixPerms = function() { + console.log("fix and refresh fitness permissions"); + return checkOrFix(fitnessPermissionsCheck, $window.cordova.plugins.BEMDataCollection.fixFitnessPermissions, + $scope.recomputeFitnessStatus, showError=true); }; + let checkPerms = function() { + console.log("fix and refresh fitness permissions"); + return checkOrFix(fitnessPermissionsCheck, $window.cordova.plugins.BEMDataCollection.isValidFitnessPermissions, + $scope.recomputeFitnessStatus, showError=false); + }; + let fitnessPermissionsCheck = { name: $translate.instant("intro.appstatus.fitnessperms.name"), desc: $translate.instant("intro.appstatus.fitnessperms.description.android"), - statusIcon: "✅", - statusClass: "status-green", - fix: fixAndRefreshPermissionsPlaceholder, - refresh: fixAndRefreshPermissionsPlaceholder + fix: fixPerms, + refresh: checkPerms } $scope.fitnessChecks = [fitnessPermissionsCheck]; - $scope.overallFitnessStatusIcon = "✅"; - $scope.overallFitnessStatusClass = "status-green"; + let fitnessCheckPromises = $scope.fitnessChecks.map((fc) => fc.refresh()); + console.log(fitnessCheckPromises); + Promise.all(fitnessCheckPromises) + .then((result) => $scope.recomputeFitnessStatus()) + .catch((error) => $scope.recomputeFitnessStatus()) } $scope.setupPermissionText = function() { From e9cd270c81a69ff911808a7abbfb87990bc4c1d6 Mon Sep 17 00:00:00 2001 From: "K. Shankari" Date: Fri, 29 Oct 2021 10:15:23 -0700 Subject: [PATCH 055/175] Enable notification enabled checks Follow on to https://github.com/e-mission/e-mission-phone/pull/804/commits/29d2d855acfb7bf91b6bffde1ab8bb94c6fb1a4c https://github.com/e-mission/e-mission-phone/pull/804/commits/ec764686a53a39ae66479d4a0db7b6aaf0862fdc --- www/i18n/en.json | 9 ++++ www/js/appstatus/permissioncheck.js | 48 ++++++++++++++++++++ www/templates/appstatus/permissioncheck.html | 24 +++++++--- 3 files changed, 75 insertions(+), 6 deletions(-) diff --git a/www/i18n/en.json b/www/i18n/en.json index 0d832dc68..642223fc6 100644 --- a/www/i18n/en.json +++ b/www/i18n/en.json @@ -331,6 +331,15 @@ "android": "Please allow.", "ios": "Please allow." } + }, + "notificationperms": { + "app-enabled-name": "App Notifications", + "not-paused-name": "Not Paused", + "description": { + "android-enable": "On the app settings page, ensure that all notifications and channels are enabled.", + "android-unpause": "On the app settings page, ensure that all notifications are enabled. If this doesn't fix the problem, ask for help from your admin", + "ios": "Please allow." + } } }, "permissions": { diff --git a/www/js/appstatus/permissioncheck.js b/www/js/appstatus/permissioncheck.js index ae1fe13db..adb4141a6 100644 --- a/www/js/appstatus/permissioncheck.js +++ b/www/js/appstatus/permissioncheck.js @@ -36,6 +36,16 @@ controller("PermissionCheckControl", function($scope, $element, $attrs, } } + $scope.setupNotificationChecks = function(platform, version) { + if (platform.toLowerCase() == "android") { + return $scope.setupAndroidNotificationChecks(version); + } else if (platform.toLowerCase() == "ios") { + return $scope.setupIOSNotificationChecks(version); + } else { + alert("Unknown platform, no tracking"); + } + } + let iconMap = (statusState) => statusState? "✅" : "❌"; let classMap = (statusState) => statusState? "status-green" : "status-red"; @@ -61,6 +71,17 @@ controller("PermissionCheckControl", function($scope, $element, $attrs, $scope.overallFitnessStatusClass = classMap($scope.overallFitnessStatus); } + $scope.recomputeNotificationStatus = function() { + $scope.notificationChecks.forEach((nc) => { + nc.statusIcon = iconMap(nc.statusState); + nc.statusClass = classMap(nc.statusState) + }); + $scope.overallNotificationStatus = $scope.notificationChecks.map((nc) => nc.statusState).reduce((pv, cv) => pv && cv); + console.log("overallNotificationStatus = "+$scope.overallNotificationStatus+" from ", $scope.notificationChecks); + $scope.overallNotificationStatusIcon = iconMap($scope.overallNotificationStatus); + $scope.overallNotificationStatusClass = classMap($scope.overallNotificationStatus); + } + let checkOrFix = function(checkObj, nativeFn, recomputeFn, showError=true) { return nativeFn() .then((status) => { @@ -172,6 +193,32 @@ controller("PermissionCheckControl", function($scope, $element, $attrs, .catch((error) => $scope.recomputeFitnessStatus()) } + $scope.setupAndroidNotificationChecks = function() { + let fixPerms = function() { + console.log("fix and refresh notification permissions"); + return checkOrFix(appAndChannelNotificationsCheck, $window.cordova.plugins.BEMDataCollection.fixShowNotifications, + $scope.recomputeNotificationStatus, showError=true); + }; + let checkPerms = function() { + console.log("fix and refresh notification permissions"); + return checkOrFix(appAndChannelNotificationsCheck, $window.cordova.plugins.BEMDataCollection.isValidShowNotifications, + $scope.recomputeNotificationStatus, showError=false); + }; + let appAndChannelNotificationsCheck = { + name: $translate.instant("intro.appstatus.notificationperms.app-enabled-name"), + desc: $translate.instant("intro.appstatus.notificationperms.description.android-enable"), + fix: fixPerms, + refresh: checkPerms + } + $scope.notificationChecks = [appAndChannelNotificationsCheck]; + let notificationCheckPromises = $scope.notificationChecks.map((fc) => fc.refresh()); + console.log("About to initialize notification status"); + console.log(notificationCheckPromises); + Promise.all(notificationCheckPromises) + .then((result) => $scope.recomputeNotificationStatus()) + .catch((error) => $scope.recomputeNotificationStatus()) + } + $scope.setupPermissionText = function() { if($scope.platform.toLowerCase() == "ios") { if($scope.osver < 13) { @@ -200,6 +247,7 @@ controller("PermissionCheckControl", function($scope, $element, $attrs, $scope.setupPermissionText(); $scope.setupLocChecks($scope.platform, $scope.osver); $scope.setupFitnessChecks($scope.platform, $scope.osver); + $scope.setupNotificationChecks($scope.platform, $scope.osver); }); $ionicPlatform.on("resume", function() { diff --git a/www/templates/appstatus/permissioncheck.html b/www/templates/appstatus/permissioncheck.html index 12eb19744..103839691 100644 --- a/www/templates/appstatus/permissioncheck.html +++ b/www/templates/appstatus/permissioncheck.html @@ -40,15 +40,27 @@
-
- -
-

Notifications

-We need this permission in order to prompt you for your travel mode and purpose. -Please allow.
+
+

Notifications {{overallNotificationStatusIcon}}

+We need to use notifications to inform you if the settings are incorrect. We also use notifications to remind you to label your trips. + + +
+
{{notificationCheck.name}}
+
{{notificationCheck.statusIcon}}
+
+
{{notificationCheck.desc}}
+
+ + +
+
+
+
+

Allow background restrictions

Your phone restricts app operation in the background. This prevents the app From 2b0cf26bc82af93184ab099b99d54d97182745e8 Mon Sep 17 00:00:00 2001 From: "K. Shankari" Date: Fri, 29 Oct 2021 11:47:52 -0700 Subject: [PATCH 056/175] Adding support for checking paused notifications Will revert this check in the next commit since it is not very relevant right now https://github.com/e-mission/e-mission-docs/issues/680#issuecomment-954958935 --- www/i18n/en.json | 2 +- www/js/appstatus/permissioncheck.js | 18 +++++++++++++++++- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/www/i18n/en.json b/www/i18n/en.json index 642223fc6..9da74eaf5 100644 --- a/www/i18n/en.json +++ b/www/i18n/en.json @@ -337,7 +337,7 @@ "not-paused-name": "Not Paused", "description": { "android-enable": "On the app settings page, ensure that all notifications and channels are enabled.", - "android-unpause": "On the app settings page, ensure that all notifications are enabled. If this doesn't fix the problem, ask for help from your admin", + "android-unpause": "App is suspended or marked as 'distracting'. Please report to your admin.", "ios": "Please allow." } } diff --git a/www/js/appstatus/permissioncheck.js b/www/js/appstatus/permissioncheck.js index adb4141a6..4cd1b1e9e 100644 --- a/www/js/appstatus/permissioncheck.js +++ b/www/js/appstatus/permissioncheck.js @@ -204,13 +204,29 @@ controller("PermissionCheckControl", function($scope, $element, $attrs, return checkOrFix(appAndChannelNotificationsCheck, $window.cordova.plugins.BEMDataCollection.isValidShowNotifications, $scope.recomputeNotificationStatus, showError=false); }; + let fixPaused = function() { + console.log("refresh notification pause status"); + return checkOrFix(appUnpausedCheck, $window.cordova.plugins.BEMDataCollection.isNotificationsUnpaused, + $scope.recomputeNotificationStatus, showError=true); + }; + let checkPaused = function() { + console.log("refresh notification pause status"); + return checkOrFix(appUnpausedCheck, $window.cordova.plugins.BEMDataCollection.isNotificationsUnpaused, + $scope.recomputeNotificationStatus, showError=false); + }; let appAndChannelNotificationsCheck = { name: $translate.instant("intro.appstatus.notificationperms.app-enabled-name"), desc: $translate.instant("intro.appstatus.notificationperms.description.android-enable"), fix: fixPerms, refresh: checkPerms } - $scope.notificationChecks = [appAndChannelNotificationsCheck]; + let appUnpausedCheck = { + name: $translate.instant("intro.appstatus.notificationperms.not-paused-name"), + desc: $translate.instant("intro.appstatus.notificationperms.description.android-unpause"), + fix: fixPaused, + refresh: checkPaused + } + $scope.notificationChecks = [appAndChannelNotificationsCheck, appUnpausedCheck]; let notificationCheckPromises = $scope.notificationChecks.map((fc) => fc.refresh()); console.log("About to initialize notification status"); console.log(notificationCheckPromises); From bfa4bf3774cd6eefd5be82929af203edbca3fabd Mon Sep 17 00:00:00 2001 From: "K. Shankari" Date: Fri, 29 Oct 2021 11:48:57 -0700 Subject: [PATCH 057/175] Revert "Adding support for checking paused notifications" This reverts commit 2b0cf26bc82af93184ab099b99d54d97182745e8. Consistent with https://github.com/e-mission/e-mission-docs/issues/680#issuecomment-954958935 We can enable the functionality later using a UI-only change if needed --- www/i18n/en.json | 2 +- www/js/appstatus/permissioncheck.js | 18 +----------------- 2 files changed, 2 insertions(+), 18 deletions(-) diff --git a/www/i18n/en.json b/www/i18n/en.json index 9da74eaf5..642223fc6 100644 --- a/www/i18n/en.json +++ b/www/i18n/en.json @@ -337,7 +337,7 @@ "not-paused-name": "Not Paused", "description": { "android-enable": "On the app settings page, ensure that all notifications and channels are enabled.", - "android-unpause": "App is suspended or marked as 'distracting'. Please report to your admin.", + "android-unpause": "On the app settings page, ensure that all notifications are enabled. If this doesn't fix the problem, ask for help from your admin", "ios": "Please allow." } } diff --git a/www/js/appstatus/permissioncheck.js b/www/js/appstatus/permissioncheck.js index 4cd1b1e9e..adb4141a6 100644 --- a/www/js/appstatus/permissioncheck.js +++ b/www/js/appstatus/permissioncheck.js @@ -204,29 +204,13 @@ controller("PermissionCheckControl", function($scope, $element, $attrs, return checkOrFix(appAndChannelNotificationsCheck, $window.cordova.plugins.BEMDataCollection.isValidShowNotifications, $scope.recomputeNotificationStatus, showError=false); }; - let fixPaused = function() { - console.log("refresh notification pause status"); - return checkOrFix(appUnpausedCheck, $window.cordova.plugins.BEMDataCollection.isNotificationsUnpaused, - $scope.recomputeNotificationStatus, showError=true); - }; - let checkPaused = function() { - console.log("refresh notification pause status"); - return checkOrFix(appUnpausedCheck, $window.cordova.plugins.BEMDataCollection.isNotificationsUnpaused, - $scope.recomputeNotificationStatus, showError=false); - }; let appAndChannelNotificationsCheck = { name: $translate.instant("intro.appstatus.notificationperms.app-enabled-name"), desc: $translate.instant("intro.appstatus.notificationperms.description.android-enable"), fix: fixPerms, refresh: checkPerms } - let appUnpausedCheck = { - name: $translate.instant("intro.appstatus.notificationperms.not-paused-name"), - desc: $translate.instant("intro.appstatus.notificationperms.description.android-unpause"), - fix: fixPaused, - refresh: checkPaused - } - $scope.notificationChecks = [appAndChannelNotificationsCheck, appUnpausedCheck]; + $scope.notificationChecks = [appAndChannelNotificationsCheck]; let notificationCheckPromises = $scope.notificationChecks.map((fc) => fc.refresh()); console.log("About to initialize notification status"); console.log(notificationCheckPromises); From feca14cade39db2c6a8f4d9f01ab13ed37d12a22 Mon Sep 17 00:00:00 2001 From: "K. Shankari" Date: Sun, 31 Oct 2021 14:38:03 -0700 Subject: [PATCH 058/175] Bump up the java version to 11 To be consistent with https://github.com/e-mission/e-mission-docs/issues/680#issuecomment-955125988 Update the README to indicate that we need to install java 11 Update the github workflow to set the JAVA_HOME to java 11 before building --- .github/workflows/android-build.yml | 7 ++++++- README.md | 4 +--- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/.github/workflows/android-build.yml b/.github/workflows/android-build.yml index f16b8dd7d..74ad7fafa 100644 --- a/.github/workflows/android-build.yml +++ b/.github/workflows/android-build.yml @@ -27,7 +27,10 @@ jobs: # Runs a single command using the runners shell - name: Print the java version - run: java -version + run: | + java -version + export JAVA_HOME=JAVA_HOME_11_X64 + java -version - name: Tries to figure out where android is installed run: | @@ -42,6 +45,7 @@ jobs: - name: Check tool versions shell: bash -l {0} run: | + export JAVA_HOME=JAVA_HOME_11_X64 source setup/activate_native.sh echo "cordova version" npx cordova -version @@ -59,6 +63,7 @@ jobs: gradle -version echo "Let's rerun the activation" source setup/activate_native.sh + export JAVA_HOME=JAVA_HOME_11_X64 echo $PATH which gradle gradle --version diff --git a/README.md b/README.md index d26697a40..3b932685a 100644 --- a/README.md +++ b/README.md @@ -95,9 +95,7 @@ Pre-requisites - **NOTE**: the basic xcode install on Catalina was messed up for me due to a prior installation of command line tools. [These workarounds helped](https://github.com/nodejs/node-gyp/blob/master/macOS_Catalina.md). - git - the most recent version of android studio - - **NOTE**: although Catalina has a `/usr/bin/java`, trying to run it gives the error `No Java runtime present, requesting install.`. Installed [OpenJDK 1.8 using AdoptOpenJDK](https://adoptopenjdk.net/releases.html) to be consistent with the CI. - - NOTE: The setup script below will modify this install to workaround - https://github.com/actions/virtual-environments/issues/3757 + - **NOTE**: although Catalina has a `/usr/bin/java`, trying to run it gives the error `No Java runtime present, requesting install.`. The build now requires Java 11. Installed [OpenJDK 11 (Temurin) using AdoptOpenJDK](https://adoptopenjdk.net/releases.html) to be consistent with the CI. Important --- From 03740dfaa9d6005f87ef606457aeed4c49705f69 Mon Sep 17 00:00:00 2001 From: "K. Shankari" Date: Sun, 31 Oct 2021 15:01:51 -0700 Subject: [PATCH 059/175] Fix the code that sets the JAVA_HOME correctly --- .github/workflows/android-build.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/android-build.yml b/.github/workflows/android-build.yml index 74ad7fafa..62d075a2c 100644 --- a/.github/workflows/android-build.yml +++ b/.github/workflows/android-build.yml @@ -29,7 +29,7 @@ jobs: - name: Print the java version run: | java -version - export JAVA_HOME=JAVA_HOME_11_X64 + export JAVA_HOME=$JAVA_HOME_11_X64 java -version - name: Tries to figure out where android is installed @@ -45,7 +45,7 @@ jobs: - name: Check tool versions shell: bash -l {0} run: | - export JAVA_HOME=JAVA_HOME_11_X64 + export JAVA_HOME=$JAVA_HOME_11_X64 source setup/activate_native.sh echo "cordova version" npx cordova -version @@ -63,7 +63,7 @@ jobs: gradle -version echo "Let's rerun the activation" source setup/activate_native.sh - export JAVA_HOME=JAVA_HOME_11_X64 + export JAVA_HOME=$JAVA_HOME_11_X64 echo $PATH which gradle gradle --version From fc8d0e294f6244422800ab14f8c9f1b57296c1f0 Mon Sep 17 00:00:00 2001 From: "K. Shankari" Date: Mon, 1 Nov 2021 17:49:55 -0700 Subject: [PATCH 060/175] Add the new unused app restrictions to the status screen Fairly straightforward change similar to prior changes for location and motion activity. The one "special" difference is that we move the buttons out of the directive and into the top level intro, which is where it makes sense in the long term anyway. We should have separate top level directives for the individual sensors that we use. --- www/i18n/en.json | 7 +++ www/js/appstatus/permissioncheck.js | 48 ++++++++++++++++++++ www/templates/appstatus/permissioncheck.html | 39 +++++++++------- www/templates/intro/sensor_explanation.html | 11 +++++ 4 files changed, 89 insertions(+), 16 deletions(-) diff --git a/www/i18n/en.json b/www/i18n/en.json index 642223fc6..fb5cf1b1b 100644 --- a/www/i18n/en.json +++ b/www/i18n/en.json @@ -340,6 +340,13 @@ "android-unpause": "On the app settings page, ensure that all notifications are enabled. If this doesn't fix the problem, ask for help from your admin", "ios": "Please allow." } + }, + "unusedapprestrict": { + "name": "Unused apps disabled", + "description": { + "android-disable": "On the app settings page, go to 'Permissions' and ensure that the app permissions will not be automatically reset.", + "ios": "Please allow." + } } }, "permissions": { diff --git a/www/js/appstatus/permissioncheck.js b/www/js/appstatus/permissioncheck.js index adb4141a6..f91b4b93a 100644 --- a/www/js/appstatus/permissioncheck.js +++ b/www/js/appstatus/permissioncheck.js @@ -46,6 +46,16 @@ controller("PermissionCheckControl", function($scope, $element, $attrs, } } + $scope.setupBackgroundRestrictionChecks = function(platform, version) { + if (platform.toLowerCase() == "android") { + return $scope.setupAndroidBackgroundRestrictionChecks(version); + } else if (platform.toLowerCase() == "ios") { + return $scope.setupIOSBackgroundRestrictionChecks(version); + } else { + alert("Unknown platform, no tracking"); + } + } + let iconMap = (statusState) => statusState? "✅" : "❌"; let classMap = (statusState) => statusState? "status-green" : "status-red"; @@ -82,6 +92,17 @@ controller("PermissionCheckControl", function($scope, $element, $attrs, $scope.overallNotificationStatusClass = classMap($scope.overallNotificationStatus); } + $scope.recomputeBackgroundRestrictionStatus = function() { + $scope.backgroundRestrictionChecks.forEach((brc) => { + brc.statusIcon = iconMap(brc.statusState); + brc.statusClass = classMap(brc.statusState) + }); + $scope.overallBackgroundRestrictionStatus = $scope.backgroundRestrictionChecks.map((nc) => nc.statusState).reduce((pv, cv) => pv && cv); + console.log("overallBackgroundRestrictionStatus = "+$scope.overallBackgroundRestrictionStatus+" from ", $scope.backgroundRestrictionChecks); + $scope.overallBackgroundRestrictionStatusIcon = iconMap($scope.overallBackgroundRestrictionStatus); + $scope.overallBackgroundRestrictionStatusClass = classMap($scope.overallBackgroundRestrictionStatus); + } + let checkOrFix = function(checkObj, nativeFn, recomputeFn, showError=true) { return nativeFn() .then((status) => { @@ -219,6 +240,32 @@ controller("PermissionCheckControl", function($scope, $element, $attrs, .catch((error) => $scope.recomputeNotificationStatus()) } + $scope.setupAndroidBackgroundRestrictionChecks = function() { + let fixPerms = function() { + console.log("fix and refresh backgroundRestriction permissions"); + return checkOrFix(unusedAppsUnrestrictedCheck, $window.cordova.plugins.BEMDataCollection.fixUnusedAppRestrictions, + $scope.recomputeBackgroundRestrictionStatus, showError=true); + }; + let checkPerms = function() { + console.log("fix and refresh backgroundRestriction permissions"); + return checkOrFix(unusedAppsUnrestrictedCheck, $window.cordova.plugins.BEMDataCollection.isUnusedAppUnrestricted, + $scope.recomputeBackgroundRestrictionStatus, showError=false); + }; + let unusedAppsUnrestrictedCheck = { + name: $translate.instant("intro.appstatus.unusedapprestrict.name"), + desc: $translate.instant("intro.appstatus.unusedapprestrict.description.android-disable"), + fix: fixPerms, + refresh: checkPerms + } + $scope.backgroundRestrictionChecks = [unusedAppsUnrestrictedCheck]; + let backgroundRestrictionCheckPromises = $scope.backgroundRestrictionChecks.map((fc) => fc.refresh()); + console.log("About to initialize backgroundRestriction status"); + console.log(backgroundRestrictionCheckPromises); + Promise.all(backgroundRestrictionCheckPromises) + .then((result) => $scope.recomputeBackgroundRestrictionStatus()) + .catch((error) => $scope.recomputeBackgroundRestrictionStatus()) + } + $scope.setupPermissionText = function() { if($scope.platform.toLowerCase() == "ios") { if($scope.osver < 13) { @@ -248,6 +295,7 @@ controller("PermissionCheckControl", function($scope, $element, $attrs, $scope.setupLocChecks($scope.platform, $scope.osver); $scope.setupFitnessChecks($scope.platform, $scope.osver); $scope.setupNotificationChecks($scope.platform, $scope.osver); + $scope.setupBackgroundRestrictionChecks($scope.platform, $scope.osver); }); $ionicPlatform.on("resume", function() { diff --git a/www/templates/appstatus/permissioncheck.html b/www/templates/appstatus/permissioncheck.html index 103839691..cbff6bee9 100644 --- a/www/templates/appstatus/permissioncheck.html +++ b/www/templates/appstatus/permissioncheck.html @@ -61,21 +61,28 @@ -
-

Allow background restrictions

-Your phone restricts app operation in the background. This prevents the app -from tracking your location or pushing it to the server. Please enable -background operation for this app with the following instructions: -{{allowBackgroundRestrictions}}. -
+
+

Background restrictions {{overallBackgroundRestrictionIcon}}

+ +The app runs in the background most of the time to make your life easier. You +only need to open it periodically to label trips. Android sometimes restricts +apps from working in the background. This prevents us from generating an +accurate trip diary. Please remove background restrictions on this app. + + + +
+
{{backgroundRestrictionCheck.name}}
+
{{backgroundRestrictionCheck.statusIcon}}
+
+
{{backgroundRestrictionCheck.desc}}
+
+ + +
+
+
+
-
-
- -
-
- -
-
- + diff --git a/www/templates/intro/sensor_explanation.html b/www/templates/intro/sensor_explanation.html index 0cd1ba4fb..e7be7fcd9 100644 --- a/www/templates/intro/sensor_explanation.html +++ b/www/templates/intro/sensor_explanation.html @@ -7,4 +7,15 @@ +
+
+ +
+
+ +
+
+
+ + From 37e327adda5a3daac9c294623aecd37034ea95bf Mon Sep 17 00:00:00 2001 From: "K. Shankari" Date: Fri, 12 Nov 2021 18:00:59 -0800 Subject: [PATCH 061/175] UI changes to handle the "deny" use case correctly This is the complement to https://github.com/e-mission/e-mission-data-collection/pull/195/commits/61a7b8b99ffecd22acc41e9644429b75f5f8312f It primarily changes the instructions displayed to the user to be consistent with the actual operations they need to do. TODO: Do something more sophisticated than just displaying the error message. Return an error code in addition to the message and use it to look up the UI displayed message. --- www/js/appstatus/permissioncheck.js | 4 +++- www/templates/appstatus/permissioncheck.html | 5 ++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/www/js/appstatus/permissioncheck.js b/www/js/appstatus/permissioncheck.js index f91b4b93a..2d0555ebc 100644 --- a/www/js/appstatus/permissioncheck.js +++ b/www/js/appstatus/permissioncheck.js @@ -48,8 +48,10 @@ controller("PermissionCheckControl", function($scope, $element, $attrs, $scope.setupBackgroundRestrictionChecks = function(platform, version) { if (platform.toLowerCase() == "android") { + $scope.backgroundUnrestrictionsNeeded = true; return $scope.setupAndroidBackgroundRestrictionChecks(version); } else if (platform.toLowerCase() == "ios") { + $scope.backgroundUnrestrictionsNeeded = false; return $scope.setupIOSBackgroundRestrictionChecks(version); } else { alert("Unknown platform, no tracking"); @@ -143,7 +145,7 @@ controller("PermissionCheckControl", function($scope, $element, $attrs, let fixPerms = function() { console.log("fix and refresh location permissions"); return checkOrFix(locPermissionsCheck, $window.cordova.plugins.BEMDataCollection.fixLocationPermissions, - $scope.recomputeLocStatus, showError=true); + $scope.recomputeLocStatus, showError=true).then((error) => locPermissionsCheck.desc = error); }; let checkPerms = function() { console.log("fix and refresh location permissions"); diff --git a/www/templates/appstatus/permissioncheck.html b/www/templates/appstatus/permissioncheck.html index cbff6bee9..ced14a9ca 100644 --- a/www/templates/appstatus/permissioncheck.html +++ b/www/templates/appstatus/permissioncheck.html @@ -61,8 +61,9 @@ +
-

Background restrictions {{overallBackgroundRestrictionIcon}}

+

Background restrictions {{overallBackgroundRestrictionStatusIcon}}

The app runs in the background most of the time to make your life easier. You only need to open it periodically to label trips. Android sometimes restricts @@ -83,6 +84,4 @@
-
- From f3ab75af5e2ce0ec4e4da220de32bf57a9c2e31d Mon Sep 17 00:00:00 2001 From: "K. Shankari" Date: Fri, 12 Nov 2021 18:50:02 -0800 Subject: [PATCH 062/175] Follow on to also update the instructions for the motion activity Follow-on to https://github.com/e-mission/e-mission-data-collection/pull/195/commits/61a7b8b99ffecd22acc41e9644429b75f5f8312f --- www/js/appstatus/permissioncheck.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/www/js/appstatus/permissioncheck.js b/www/js/appstatus/permissioncheck.js index 2d0555ebc..d9d993bfd 100644 --- a/www/js/appstatus/permissioncheck.js +++ b/www/js/appstatus/permissioncheck.js @@ -194,7 +194,7 @@ controller("PermissionCheckControl", function($scope, $element, $attrs, let fixPerms = function() { console.log("fix and refresh fitness permissions"); return checkOrFix(fitnessPermissionsCheck, $window.cordova.plugins.BEMDataCollection.fixFitnessPermissions, - $scope.recomputeFitnessStatus, showError=true); + $scope.recomputeFitnessStatus, showError=true).then((error) => fitnessPermissionsCheck.desc = error); }; let checkPerms = function() { console.log("fix and refresh fitness permissions"); From 570c87d96486b72ce5dc337e300897d893b9937e Mon Sep 17 00:00:00 2001 From: "K. Shankari" Date: Tue, 16 Nov 2021 20:42:30 -0800 Subject: [PATCH 063/175] Enhance the local notification handling and redirection code - Read state params in addition to the target state - fix foreground check - handle notifications on both android and iOS --- www/js/splash/localnotify.js | 24 +++++++++++------------- www/js/splash/startprefs.js | 4 +++- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/www/js/splash/localnotify.js b/www/js/splash/localnotify.js index dde7012bc..1df884526 100644 --- a/www/js/splash/localnotify.js +++ b/www/js/splash/localnotify.js @@ -17,17 +17,18 @@ angular.module('emission.splash.localnotify', ['emission.plugin.logger', localNotify.getRedirectState = function(notification) { // TODO: Think whether this should be in data or in category if (angular.isDefined(notification.data)) { - return notification.data.redirectTo; + return [notification.data.redirectTo, notification.data.redirectParams]; } return undefined; } - localNotify.handleLaunch = function(targetState) { + localNotify.handleLaunch = function(targetState, targetParams) { $rootScope.redirectTo = targetState; - $state.go(targetState); + $rootScope.redirectParams = targetParams; + $state.go(targetState, targetParams); } - localNotify.handlePrompt = function(notification, targetState) { + localNotify.handlePrompt = function(notification, targetState, targetParams) { Logger.log("Prompting for notification "+notification.title+" and text "+notification.text); var promptPromise = $ionicPopup.show({title: notification.title, template: notification.text, @@ -48,7 +49,7 @@ angular.module('emission.splash.localnotify', ['emission.plugin.logger', }); promptPromise.then(function(handle) { if (handle == true) { - localNotify.handleLaunch(targetState); + localNotify.handleLaunch(targetState, targetParams); } else { Logger.log("Ignoring notification "+notification.title+" and text "+notification.text); } @@ -56,13 +57,13 @@ angular.module('emission.splash.localnotify', ['emission.plugin.logger', } localNotify.handleNotification = function(notification,state,data) { - var targetState = localNotify.getRedirectState(notification); + var [targetState, targetParams] = localNotify.getRedirectState(notification); Logger.log("targetState = "+targetState); if (angular.isDefined(targetState)) { - if (state == "foreground") { - localNotify.handlePrompt(notification, targetState); + if (state.foreground == true) { + localNotify.handlePrompt(notification, targetState, targetParams); } else { - localNotify.handleLaunch(targetState); + localNotify.handleLaunch(targetState, targetParams); } } } @@ -79,10 +80,7 @@ angular.module('emission.splash.localnotify', ['emission.plugin.logger', // alert("notification cancelled, no report"); }); $window.cordova.plugins.notification.local.on('trigger', function (notification, state, data) { - Logger.log("triggered, no action"); - if ($ionicPlatform.is('ios')) { - localNotify.handleNotification(notification, state, data); - } + localNotify.handleNotification(notification, state, data); }); $window.cordova.plugins.notification.local.on('click', function (notification, state, data) { localNotify.handleNotification(notification, state, data); diff --git a/www/js/splash/startprefs.js b/www/js/splash/startprefs.js index e18c4054d..0ee47fc81 100644 --- a/www/js/splash/startprefs.js +++ b/www/js/splash/startprefs.js @@ -172,8 +172,10 @@ angular.module('emission.splash.startprefs', ['emission.plugin.logger', return {state: 'root.main.diary'}; } else if (angular.isDefined($rootScope.redirectTo)) { var redirState = $rootScope.redirectTo; + var redirParams = $rootScope.redirectParams; $rootScope.redirectTo = undefined; - return {state: redirState, params: {}}; + $rootScope.redirectParams = undefined; + return {state: redirState, params: redirParams}; } else { return {state: 'root.main.inf_scroll', params: {}}; } From 07dfa939185e2cd33441d1d5fd3600e660333919 Mon Sep 17 00:00:00 2001 From: "K. Shankari" Date: Wed, 17 Nov 2021 00:16:35 -0800 Subject: [PATCH 064/175] Allow the user to proceed only when they have made all the settings correct - Define an "overallstatus" variable - pass it in from the permission check directive - change the directive to accept it - add a new `recomputeOverallStatus` method that is called from each of the recompute methods - add a disabled flag to the "I agree" based on the overallStatus Since there is a bi-directional binding between the parent scope and the directive scope, changing the directive scope updates the parent and enables the "I agree" button. --- www/js/appstatus/permissioncheck.js | 14 +++++++++++++- www/js/intro.js | 2 ++ www/templates/intro/sensor_explanation.html | 5 +++-- 3 files changed, 18 insertions(+), 3 deletions(-) diff --git a/www/js/appstatus/permissioncheck.js b/www/js/appstatus/permissioncheck.js index d9d993bfd..fd55cd0a8 100644 --- a/www/js/appstatus/permissioncheck.js +++ b/www/js/appstatus/permissioncheck.js @@ -7,6 +7,7 @@ angular.module('emission.appstatus.permissioncheck', .directive('permissioncheck', function() { return { scope: { + overallstatus: "=", }, controller: "PermissionCheckControl", templateUrl: "templates/appstatus/permissioncheck.html" @@ -14,7 +15,7 @@ angular.module('emission.appstatus.permissioncheck', }). controller("PermissionCheckControl", function($scope, $element, $attrs, $ionicPlatform, $ionicPopup, $window, $translate) { - console.log("PermissionCheckControl initialized"); + console.log("PermissionCheckControl initialized with status "+$scope.overallstatus); $scope.setupLocChecks = function(platform, version) { if (platform.toLowerCase() == "android") { @@ -61,6 +62,13 @@ controller("PermissionCheckControl", function($scope, $element, $attrs, let iconMap = (statusState) => statusState? "✅" : "❌"; let classMap = (statusState) => statusState? "status-green" : "status-red"; + $scope.recomputeOverallStatus = function() { + $scope.overallstatus = $scope.overallLocStatus + && $scope.overallFitnessStatus + && $scope.overallNotificationStatus + && $scope.overallBackgroundRestrictionStatus; + } + $scope.recomputeLocStatus = function() { $scope.locChecks.forEach((lc) => { lc.statusIcon = iconMap(lc.statusState); @@ -70,6 +78,7 @@ controller("PermissionCheckControl", function($scope, $element, $attrs, console.log("overallLocStatus = "+$scope.overallLocStatus+" from ", $scope.locChecks); $scope.overallLocStatusIcon = iconMap($scope.overallLocStatus); $scope.overallLocStatusClass = classMap($scope.overallLocStatus); + $scope.recomputeOverallStatus(); } $scope.recomputeFitnessStatus = function() { @@ -81,6 +90,7 @@ controller("PermissionCheckControl", function($scope, $element, $attrs, console.log("overallFitnessStatus = "+$scope.overallFitnessStatus+" from ", $scope.fitnessChecks); $scope.overallFitnessStatusIcon = iconMap($scope.overallFitnessStatus); $scope.overallFitnessStatusClass = classMap($scope.overallFitnessStatus); + $scope.recomputeOverallStatus(); } $scope.recomputeNotificationStatus = function() { @@ -92,6 +102,7 @@ controller("PermissionCheckControl", function($scope, $element, $attrs, console.log("overallNotificationStatus = "+$scope.overallNotificationStatus+" from ", $scope.notificationChecks); $scope.overallNotificationStatusIcon = iconMap($scope.overallNotificationStatus); $scope.overallNotificationStatusClass = classMap($scope.overallNotificationStatus); + $scope.recomputeOverallStatus(); } $scope.recomputeBackgroundRestrictionStatus = function() { @@ -103,6 +114,7 @@ controller("PermissionCheckControl", function($scope, $element, $attrs, console.log("overallBackgroundRestrictionStatus = "+$scope.overallBackgroundRestrictionStatus+" from ", $scope.backgroundRestrictionChecks); $scope.overallBackgroundRestrictionStatusIcon = iconMap($scope.overallBackgroundRestrictionStatus); $scope.overallBackgroundRestrictionStatusClass = classMap($scope.overallBackgroundRestrictionStatus); + $scope.recomputeOverallStatus(); } let checkOrFix = function(checkObj, nativeFn, recomputeFn, showError=true) { diff --git a/www/js/intro.js b/www/js/intro.js index 9a8ff4627..a8ba7a200 100644 --- a/www/js/intro.js +++ b/www/js/intro.js @@ -66,6 +66,8 @@ angular.module('emission.intro', ['emission.splash.startprefs', }); }; + $scope.overallStatus = false; + $scope.disagree = function() { $state.go('root.main.heatmap'); }; diff --git a/www/templates/intro/sensor_explanation.html b/www/templates/intro/sensor_explanation.html index e7be7fcd9..bb90536ed 100644 --- a/www/templates/intro/sensor_explanation.html +++ b/www/templates/intro/sensor_explanation.html @@ -5,17 +5,18 @@ + From 539a0fdc9df8af2b436dd23a852364bf50d0c1b1 Mon Sep 17 00:00:00 2001 From: "K. Shankari" Date: Wed, 17 Nov 2021 02:10:09 -0800 Subject: [PATCH 065/175] Add a new entry to the profile screen which opens the app status modal - Declare the app status modal - write functions to show and hide it - hook up the show to the profile UI - hook up the hide to a successful fix of the permissions The status modal is very similar to the intro screen, down to the shared `overallstatus` scope and the enable/disable based on it --- www/i18n/en.json | 4 +++- www/js/control/general-settings.js | 21 ++++++++++++++++++++- www/templates/control/app-status-modal.html | 12 ++++++++++++ www/templates/control/main-control.html | 4 ++++ 4 files changed, 39 insertions(+), 2 deletions(-) create mode 100644 www/templates/control/app-status-modal.html diff --git a/www/i18n/en.json b/www/i18n/en.json index fb5cf1b1b..a1e979a9a 100644 --- a/www/i18n/en.json +++ b/www/i18n/en.json @@ -53,6 +53,7 @@ "control":{ "profile": "Profile", "tracking": "Tracking", + "app-status": "App Status", "medium-accuracy": "Medium accuracy", "dark-theme": "Dark theme", "force-sync": "Force sync", @@ -77,7 +78,8 @@ "check-map": "Check map", "collection": "Collection", "sync": "Sync", - "transition-notify": "Transition Notify" + "transition-notify": "Transition Notify", + "button-accept": "I accept" }, "general-settings":{ diff --git a/www/js/control/general-settings.js b/www/js/control/general-settings.js index 8735f15eb..32829cefa 100644 --- a/www/js/control/general-settings.js +++ b/www/js/control/general-settings.js @@ -17,6 +17,7 @@ angular.module('emission.main.control',['emission.services', .controller('ControlCtrl', function($scope, $window, $ionicScrollDelegate, $ionicPlatform, $state, $ionicPopup, $ionicActionSheet, $ionicPopover, + $ionicModal, $rootScope, KVStore, ionicDatePicker, StartPrefs, ControlHelper, EmailHelper, UploadHelper, ControlCollectionHelper, ControlSyncHelper, @@ -26,6 +27,8 @@ angular.module('emission.main.control',['emission.services', CalorieCal, ClientStats, CommHelper, Logger, $translate) { + console.log("controller ControlCtrl called without params"); + var datepickerObject = { todayLabel: $translate.instant('list-datepicker-today'), //Optional closeLabel: $translate.instant('list-datepicker-close'), //Optional @@ -49,6 +52,14 @@ angular.module('emission.main.control',['emission.services', closeOnSelect: true //Optional } + $scope.overallAppStatus = false; + + $ionicModal.fromTemplateUrl('templates/control/app-status-modal.html', { + scope: $scope + }).then(function(modal) { + $scope.appStatusModal = modal; + }); + $scope.openDatePicker = function(){ ionicDatePicker.openDatePicker(datepickerObject); }; @@ -80,6 +91,14 @@ angular.module('emission.main.control',['emission.services', } } + $scope.fixAppStatus = function() { + $scope.appStatusModal.show(); + } + + $scope.appStatusChecked = function() { + $scope.appStatusModal.hide(); + } + $scope.userData = [] $scope.getUserData = function() { return CalorieCal.get().then(function(userDataFromStorage) { @@ -276,7 +295,7 @@ angular.module('emission.main.control',['emission.services', $scope.$on('$ionicView.afterEnter', function() { $ionicPlatform.ready().then(function() { - $scope.refreshScreen(); + $scope.refreshScreen(); }); }) diff --git a/www/templates/control/app-status-modal.html b/www/templates/control/app-status-modal.html new file mode 100644 index 000000000..954ff528a --- /dev/null +++ b/www/templates/control/app-status-modal.html @@ -0,0 +1,12 @@ + + +

Permissions

+
+ + Please fix any incorrect permissions! + +
+ +
+
+
diff --git a/www/templates/control/main-control.html b/www/templates/control/main-control.html index f5ff13c98..e8858b451 100644 --- a/www/templates/control/main-control.html +++ b/www/templates/control/main-control.html @@ -17,6 +17,10 @@
+
+
{{'.app-status'}}
+
+
{{'.medium-accuracy'}}
+
{{'.average'}} {{carbonData.aggrCarbon}}
+
{{'.lastweek'}} {{carbonData.lastWeekUserCarbon}}
@@ -81,8 +82,11 @@

{{'.footprint'}}

-
US 2030: {{carbonData.us2030}}
-
US 2050: {{carbonData.us2050}}
+
{{'.us-2030-goal'}} {{carbonData.us2030}}
+
{{'.us-2050-goal'}} {{carbonData.us2050}}
+
@@ -109,7 +113,7 @@

{{'.calories'}}

{{'main-metrics.equals-cookies' | translate:{cookies: numberOfCookies}:"messageformat"}}
{{'main-metrics.equals-icecream' | translate:{icecream: numberOfIceCreams}:"messageformat"}}
{{'main-metrics.equals-bananas' | translate:{bananas: numberOfBananas}:"messageformat"}}
-
+
{{caloriesData.changeInPercentage}}{{caloriesData.change}}
From 052458f906b1e5a37c8415b51c7efedeb740983e Mon Sep 17 00:00:00 2001 From: "K. Shankari" Date: Wed, 22 Dec 2021 02:43:38 -0800 Subject: [PATCH 090/175] Rename `first` to `defaultTwoWeekUserCall` for greater clarity --- www/js/metrics.js | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/www/js/metrics.js b/www/js/metrics.js index b13a9c4a2..d5a927807 100644 --- a/www/js/metrics.js +++ b/www/js/metrics.js @@ -17,7 +17,7 @@ angular.module('emission.main.metrics',['nvd3', $rootScope, $location, $state, ReferHelper, Logger, $translate) { var lastTwoWeeksQuery = true; - var first = true; + var defaultTwoWeekUserCall = true; var lastWeekCalories = 0; var lastWeekCarbon = "0 kg CO₂"; var twoWeeksAgoCarbon = ""; @@ -506,7 +506,7 @@ angular.module('emission.main.metrics',['nvd3', $ionicLoading.show({ template: $translate.instant('loading') }); - if(!first){ + if(!defaultTwoWeekUserCall){ $scope.uictrl.currentString = $translate.instant('metrics.custom'); $scope.uictrl.current = false; } @@ -546,14 +546,14 @@ angular.module('emission.main.metrics',['nvd3', $ionicLoading.hide(); console.log("user results ", results); if(results.user_metrics.length == 1){ - console.log("first = "+first); - first = false; + console.log("defaultTwoWeekUserCall = "+defaultTwoWeekUserCall); + defaultTwoWeekUserCall = false; // If there is no data from last week (ex. new user) // Don't store the any other data as last we data } $scope.fillUserValues(results.user_metrics); $scope.summaryData.defaultSummary = $scope.summaryData.userSummary; - first = false; //If there is data from last week store the data only first time + defaultTwoWeekUserCall = false; //If there is data from last week store the data only first time $scope.uictrl.showContent = true; if (angular.isDefined($scope.chartDataUser)) { $scope.$apply(function() { @@ -606,7 +606,7 @@ angular.module('emission.main.metrics',['nvd3', METRIC_LIST.forEach((m) => $scope.userTwoWeeksAgo[m] = []); - if(first){ + if(defaultTwoWeekUserCall){ for(var i in user_metrics_arr[0]) { if(seventhDayAgo.isSameOrBefore(moment.unix(user_metrics_arr[0][i].ts).utc())){ METRIC_LIST.forEach((m, idx) => $scope.userCurrentResults[m].push(user_metrics_arr[idx][i])); @@ -654,7 +654,7 @@ angular.module('emission.main.metrics',['nvd3', $scope.fillAggregateValues = function(agg_metrics_arr) { METRIC_LIST.forEach((m) => $scope.aggCurrentResults[m] = []); - if (first) { + if (defaultTwoWeekUserCall) { METRIC_LIST.forEach((m, idx) => $scope.aggCurrentResults[m] = agg_metrics_arr[idx].slice(0,7)); } else { METRIC_LIST.forEach((m, idx) => $scope.aggCurrentResults[m] = agg_metrics_arr[idx]); @@ -731,7 +731,7 @@ angular.module('emission.main.metrics',['nvd3', Math.round(CalorieCal.getuserCalories(userDurationSummary[i].values / 3600, met)) //+ ' cal' } - if(first){ + if(defaultTwoWeekUserCall){ lastWeekCalories = $scope.caloriesData.userCalories; } @@ -742,7 +742,7 @@ angular.module('emission.main.metrics',['nvd3', $scope.numberOfBananas = Math.floor($scope.caloriesData.userCalories/ $scope.food.banana); - if(first && angular.isDefined(twoWeeksAgoDurationSummary)) { + if(defaultTwoWeekUserCall && angular.isDefined(twoWeeksAgoDurationSummary)) { for (var i in twoWeeksAgoDurationSummary) { var met = $scope.getCorrectedMetFromUserData(twoWeeksAgoDurationSummary[i], twoWeeksAgoMedianSpeedSummary[i]) @@ -751,7 +751,7 @@ angular.module('emission.main.metrics',['nvd3', } } - if (first) { + if (defaultTwoWeekUserCall) { $scope.caloriesData.lastWeekUserCalories = twoWeeksAgoCalories; } else { $scope.caloriesData.lastWeekUserCalories = "" @@ -835,7 +835,7 @@ angular.module('emission.main.metrics',['nvd3', lastWeekCarbonInt = FootprintHelper.getFootprintForMetrics(userCarbonData); } - if (first) { + if (defaultTwoWeekUserCall) { if (twoWeeksAgoDistance) { var userCarbonDataTwoWeeks = getSummaryDataRaw(twoWeeksAgoDistance, 'distance'); twoWeeksAgoCarbon = 0; @@ -1220,7 +1220,7 @@ angular.module('emission.main.metrics',['nvd3', initSelect(); $scope.doRefresh = function() { - first = true; + defaultTwoWeekUserCall = true; getMetrics(); } From f4a55b2d737fb129690115ea68002a5140a70b3d Mon Sep 17 00:00:00 2001 From: "K. Shankari" Date: Wed, 22 Dec 2021 03:38:47 -0800 Subject: [PATCH 091/175] Fix the button to say "Change dates" instead of "Change data" --- www/i18n/en.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/www/i18n/en.json b/www/i18n/en.json index f39917883..a2c2f1cb6 100644 --- a/www/i18n/en.json +++ b/www/i18n/en.json @@ -213,7 +213,7 @@ "dashboard": "Dashboard", "summary": "Summary", "chart": "Chart", - "change-data": "Change data:", + "change-data": "Change dates:", "distance": "Distance", "trips": "Trips", "duration": "Duration", From a3518fee4d6f5f7243a604712c549eddfee2050f Mon Sep 17 00:00:00 2001 From: "K. Shankari" Date: Wed, 22 Dec 2021 03:56:54 -0800 Subject: [PATCH 092/175] Convert both userCarbon and the goals to numbers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit And handle the formatting in the HTML, as it should be. This allows us to deal with comparisons between the values correctly and fixes https://github.com/e-mission/e-mission-docs/issues/688#issuecomment-999231429 by fixing https://github.com/e-mission/e-mission-docs/issues/688#issuecomment-999497644 If we want to debug the comparisons, and it is hard to do so with the conditional in the HTML, we can use: ``` $scope.carbonData.us2030Color = $scope.carbonData.userCarbon > $scope.carbonData.us2030? '#DB536F !important' : ''; $scope.carbonData.us2050Color = $scope.carbonData.userCarbon > $scope.carbonData.us2050? '#DB536F !important' : ''; ``` so we can put breakpoints and figure out what is going on ```
{{'.us-2030-goal'}} {{carbonData.us2030 | number}} kg CO₂
{{'.us-2050-goal'}} {{carbonData.us2050 | number}} kg CO₂
``` --- www/js/metrics.js | 8 ++++---- www/templates/main-metrics.html | 6 +++--- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/www/js/metrics.js b/www/js/metrics.js index d5a927807..9ab8fa9ff 100644 --- a/www/js/metrics.js +++ b/www/js/metrics.js @@ -525,7 +525,7 @@ angular.module('emission.main.metrics',['nvd3', $scope.caloriesData.changeInPercentage = "0%" $scope.caloriesData.change = $translate.instant('metrics.calorie-data-change'); - $scope.carbonData.userCarbon = "0 kg CO₂"; + $scope.carbonData.userCarbon = 0; $scope.carbonData.aggrCarbon = $translate.instant('metrics.carbon-data-calculating');; $scope.carbonData.optimalCarbon = "0 kg CO₂"; $scope.carbonData.worstCarbon = "0 kg CO₂"; @@ -826,10 +826,10 @@ angular.module('emission.main.metrics',['nvd3', * than 7 days, we calculate the per day value by dividing by 7 and * then multiplying by the actual number of days. */ - $scope.carbonData.us2030 = Math.round(54 / 7 * days) + ' kg CO₂'; // kg/day - $scope.carbonData.us2050 = Math.round(14 / 7 * days) + ' kg CO₂'; + $scope.carbonData.us2030 = Math.round(54 / 7 * days); // kg/day + $scope.carbonData.us2050 = Math.round(14 / 7 * days); - $scope.carbonData.userCarbon = FootprintHelper.readableFormat(FootprintHelper.getFootprintForMetrics(userCarbonData)); + $scope.carbonData.userCarbon = FootprintHelper.getFootprintForMetrics(userCarbonData); $scope.carbonData.optimalCarbon = FootprintHelper.readableFormat(FootprintHelper.getLowestFootprintForDistance(optimalDistance)); $scope.carbonData.worstCarbon = FootprintHelper.readableFormat(FootprintHelper.getHighestFootprintForDistance(worstDistance)); lastWeekCarbonInt = FootprintHelper.getFootprintForMetrics(userCarbonData); diff --git a/www/templates/main-metrics.html b/www/templates/main-metrics.html index 81bbf96b6..0c9b6d14f 100644 --- a/www/templates/main-metrics.html +++ b/www/templates/main-metrics.html @@ -61,7 +61,7 @@

{{'.footprint'}}

-
{{carbonData.userCarbon}}
+
{{ carbonData.userCarbon | number:0 }} kg CO₂
@@ -82,8 +82,8 @@
{{'.how-it-compares'}}
-
{{'.us-2030-goal'}} {{carbonData.us2030}}
-
{{'.us-2050-goal'}} {{carbonData.us2050}}
+
{{'.us-2030-goal'}} {{carbonData.us2030 | number}} kg CO₂
+
{{'.us-2050-goal'}} {{carbonData.us2050 | number}} kg CO₂
From 8616fb01c2001d65fa159e851f26c27b117c62a4 Mon Sep 17 00:00:00 2001 From: "K. Shankari" Date: Wed, 22 Dec 2021 09:25:43 -0800 Subject: [PATCH 093/175] Fix stupid typo in imperial conversions --- www/js/config/imperial.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/www/js/config/imperial.js b/www/js/config/imperial.js index 5dd08e7de..7c3f4c560 100644 --- a/www/js/config/imperial.js +++ b/www/js/config/imperial.js @@ -30,7 +30,7 @@ angular.module('emission.config.imperial', ['emission.plugin.logger']) }; ic.getMph = function(metersPerSecond) { - return (KM_TO_MILES * ic.getKmph(metersPerSec)); + return (KM_TO_MILES * ic.getKmph(metersPerSecond)); }; ic.getFormattedDistance = USE_IMPERIAL? ic.getFormattedDistanceInMiles : ic.getFormattedDistanceInKm; From cc404654bafe5b7ce68ac6c179581c1b43615e3c Mon Sep 17 00:00:00 2001 From: "K. Shankari" Date: Wed, 22 Dec 2021 17:19:45 -0800 Subject: [PATCH 094/175] Move all the presentation values for the carbon footprint to the HTML The values calculated in the javascript are integers so we can use ng-if liberally. Key improvements: - Remove the bad, english-specific check `ng-if="uictrl.currentString == 'Last week'"` and replace it with an `if` of whether the two weeks ago values exist. So if the two weeks ago values don't exist because tracking was off, for example, we won't show an incorrect 0. We should consider if we want to handle this differently, but can do so with more judicious use of `ng-if`. - Move the checks for comparison with last week into the HTML as well - keep the check `< 0` and `> 0` so if there is no change, we will not show anything - change the text to reflect that we are not doing a week over week % change - we are not dividing by the original value. - display the aggregate only if it exists; convert it to a number - display the last week only if it exists; convert it to a number Remove initializations of all these values since we have `ng-if` in place --- www/i18n/en.json | 7 ++--- www/js/metrics.js | 53 +++++++++------------------------ www/templates/main-metrics.html | 15 ++++++---- 3 files changed, 25 insertions(+), 50 deletions(-) diff --git a/www/i18n/en.json b/www/i18n/en.json index a2c2f1cb6..a68969a35 100644 --- a/www/i18n/en.json +++ b/www/i18n/en.json @@ -126,14 +126,11 @@ "chart-no-data": "No Data Available", "trips-yaxis-number": "Number", "calorie-data-change": " change", - "carbon-data-change": " change", - "carbon-data-calculating": "Calculating...", - "carbon-data-unknown": "Unknown", "calorie-data-unknown": "Unknown...", + "greater-than-last-week": " greater than last week", + "less-than-last-week": " less than last week", "calorie-data-change-increase": " increase over a week", "calorie-data-change-decrease": " decrease over a week", - "carbon-data-change-increase": " increase over a week", - "carbon-data-change-decrease": " decrease over a week", "pick-a-date": "Pick a date", "trips": "trips", "hours": "hours", diff --git a/www/js/metrics.js b/www/js/metrics.js index 9ab8fa9ff..dd596fa66 100644 --- a/www/js/metrics.js +++ b/www/js/metrics.js @@ -526,12 +526,8 @@ angular.module('emission.main.metrics',['nvd3', $scope.caloriesData.change = $translate.instant('metrics.calorie-data-change'); $scope.carbonData.userCarbon = 0; - $scope.carbonData.aggrCarbon = $translate.instant('metrics.carbon-data-calculating');; $scope.carbonData.optimalCarbon = "0 kg CO₂"; $scope.carbonData.worstCarbon = "0 kg CO₂"; - $scope.carbonData.lastWeekUserCarbon = "0 kg CO₂"; - $scope.carbonData.changeInPercentage = "0%"; - $scope.carbonData.change = $translate.instant('metrics.carbon-data-change'); $scope.summaryData.userSummary = []; $scope.chartDataUser = {}; @@ -830,47 +826,26 @@ angular.module('emission.main.metrics',['nvd3', $scope.carbonData.us2050 = Math.round(14 / 7 * days); $scope.carbonData.userCarbon = FootprintHelper.getFootprintForMetrics(userCarbonData); - $scope.carbonData.optimalCarbon = FootprintHelper.readableFormat(FootprintHelper.getLowestFootprintForDistance(optimalDistance)); - $scope.carbonData.worstCarbon = FootprintHelper.readableFormat(FootprintHelper.getHighestFootprintForDistance(worstDistance)); - lastWeekCarbonInt = FootprintHelper.getFootprintForMetrics(userCarbonData); + $scope.carbonData.optimalCarbon = FootprintHelper.getLowestFootprintForDistance(optimalDistance); + $scope.carbonData.worstCarbon = FootprintHelper.getHighestFootprintForDistance(worstDistance); } if (defaultTwoWeekUserCall) { - if (twoWeeksAgoDistance) { + // This is a default call in which we retrieved the current week and + // the previous week of data + if (twoWeeksAgoDistance.length > 0) { + // and this user has been around long enough that they have two weeks + // of data, or they haven't turned off tracking for all of last week, + // or.... var userCarbonDataTwoWeeks = getSummaryDataRaw(twoWeeksAgoDistance, 'distance'); - twoWeeksAgoCarbon = 0; - twoWeeksAgoCarbonInt = 0; - twoWeeksAgoCarbonInt = FootprintHelper.getFootprintForMetrics(userCarbonDataTwoWeeks); + $scope.carbonData.lastWeekUserCarbon = FootprintHelper.getFootprintForMetrics(userCarbonDataTwoWeeks); - twoWeeksAgoCarbon = FootprintHelper.readableFormat(twoWeeksAgoCarbonInt); - lastWeekCarbon = twoWeeksAgoCarbon; - } - } - $scope.carbonData.lastWeekUserCarbon = lastWeekCarbon; - - var change = ""; - console.log("Running calculation with " + lastWeekCarbonInt + " and " + twoWeeksAgoCarbonInt); - var calculation = (lastWeekCarbonInt/twoWeeksAgoCarbonInt) * 100 - 100; - - // TODO: Refactor this so that we can filter out bad values ahead of time - // instead of having to work around it here - if (isValidNumber(calculation)) { - if(lastWeekCarbonInt > twoWeeksAgoCarbonInt){ - $scope.carbonData.change = $translate.instant('metrics.carbon-data-change-increase'); - $scope.carbonUp = true; - $scope.carbonDown = false; - } else { - $scope.carbonData.change = $translate.instant('metrics.carbon-data-change-decrease'); - $scope.carbonUp = false; - $scope.carbonDown = true; - } - $scope.carbonData.changeInPercentage = Math.abs(Math.round(calculation)) + "%" - } - else { - $scope.carbonData.change = ""; - $scope.carbonData.changeInPercentage = "0%"; + console.log("Running calculation with " + $scope.carbonData.userCarbon + " and " + $scope.carbonData.lastWeekUserCarbon); + console.log("Running calculation with ", $scope.carbonData); + $scope.carbonData.greaterLesserPct = ($scope.carbonData.userCarbon/$scope.carbonData.lastWeekUserCarbon) * 100 - 100; } + } }; $scope.fillFootprintAggVals = function(aggDistance) { @@ -886,7 +861,7 @@ angular.module('emission.main.metrics',['nvd3', } } - $scope.carbonData.aggrCarbon = FootprintHelper.readableFormat(FootprintHelper.getFootprintForMetrics(aggrCarbonData)); + $scope.carbonData.aggrCarbon = FootprintHelper.getFootprintForMetrics(aggrCarbonData); } }; diff --git a/www/templates/main-metrics.html b/www/templates/main-metrics.html index 0c9b6d14f..ebb0a6f73 100644 --- a/www/templates/main-metrics.html +++ b/www/templates/main-metrics.html @@ -62,10 +62,13 @@

{{'.footprint'}}

{{ carbonData.userCarbon | number:0 }} kg CO₂
-
-
-
-
{{carbonData.changeInPercentage}}{{carbonData.change}}
+
+
+
{{ carbonData.greaterLesserPct | number:0 }}% {{'metrics.greater-than-last-week' | translate }}
+
+
+
+
{{ (-1) * carbonData.greaterLesserPct | number:0 }}% {{'metrics.less-than-last-week' | translate }}
@@ -74,11 +77,11 @@
{{'.how-it-compares'}}
-
{{'.average'}} {{carbonData.aggrCarbon}}
+
{{'.average'}} {{carbonData.aggrCarbon | number:0 }} kg CO₂
-
{{'.lastweek'}} {{carbonData.lastWeekUserCarbon}}
+
{{'.lastweek'}} {{carbonData.lastWeekUserCarbon | number:0 }} kg CO₂
From 44baf2214ed5dd743ae97c435dc47a0a493c7747 Mon Sep 17 00:00:00 2001 From: "K. Shankari" Date: Wed, 22 Dec 2021 21:16:08 -0800 Subject: [PATCH 095/175] Fix the calorie calculations to be numbers instead of strings as well This is a complement to cc404654bafe5b7ce68ac6c179581c1b43615e3c but for calories. With this, we don't have any checks related to `uictrl.currentString`, which is great. ``` $ grep -r uictrl.currentString www/ | grep -v .swp www//js/metrics.js: $scope.uictrl.currentString = $translate.instant('metrics.custom'); www//templates/metrics/metrics-control.html:
{{ uictrl.currentString }}
``` --- www/js/metrics.js | 45 +++++++-------------------------- www/templates/main-metrics.html | 15 ++++++----- 2 files changed, 18 insertions(+), 42 deletions(-) diff --git a/www/js/metrics.js b/www/js/metrics.js index dd596fa66..3004a4f6e 100644 --- a/www/js/metrics.js +++ b/www/js/metrics.js @@ -520,10 +520,6 @@ angular.module('emission.main.metrics',['nvd3', $scope.carbonData = {}; $scope.summaryData = {}; $scope.caloriesData.userCalories = 0; - $scope.caloriesData.aggrCalories = 0; - $scope.caloriesData.lastWeekUserCalories = 0; - $scope.caloriesData.changeInPercentage = "0%" - $scope.caloriesData.change = $translate.instant('metrics.calorie-data-change'); $scope.carbonData.userCarbon = 0; $scope.carbonData.optimalCarbon = "0 kg CO₂"; @@ -727,10 +723,6 @@ angular.module('emission.main.metrics',['nvd3', Math.round(CalorieCal.getuserCalories(userDurationSummary[i].values / 3600, met)) //+ ' cal' } - if(defaultTwoWeekUserCall){ - lastWeekCalories = $scope.caloriesData.userCalories; - } - $scope.numberOfCookies = Math.floor($scope.caloriesData.userCalories/ $scope.food.chocolateChip); $scope.numberOfIceCreams = Math.floor($scope.caloriesData.userCalories/ @@ -738,44 +730,25 @@ angular.module('emission.main.metrics',['nvd3', $scope.numberOfBananas = Math.floor($scope.caloriesData.userCalories/ $scope.food.banana); - if(defaultTwoWeekUserCall && angular.isDefined(twoWeeksAgoDurationSummary)) { + if(defaultTwoWeekUserCall) { + if (twoWeeksAgoDurationSummary.length > 0) { for (var i in twoWeeksAgoDurationSummary) { var met = $scope.getCorrectedMetFromUserData(twoWeeksAgoDurationSummary[i], twoWeeksAgoMedianSpeedSummary[i]) twoWeeksAgoCalories += Math.round(CalorieCal.getuserCalories(twoWeeksAgoDurationSummary[i].values / 3600, met)); } - } - - if (defaultTwoWeekUserCall) { - $scope.caloriesData.lastWeekUserCalories = twoWeeksAgoCalories; - } else { - $scope.caloriesData.lastWeekUserCalories = "" - } - - - console.log("Running calorieData with " - + (lastWeekCalories) - + " and " - + (twoWeeksAgoCalories)); - // TODO: Refactor this so that we can filter out bad values ahead of time - // instead of having to work around it here - var calorieCalculation = Math.abs(Math.round((lastWeekCalories/twoWeeksAgoCalories) * 100 - 100)); - if (isValidNumber(calorieCalculation)) { - $scope.caloriesData.changeInPercentage = calorieCalculation + "%"; - if(lastWeekCalories > twoWeeksAgoCalories){ - $scope.caloriesData.change = $translate.instant('metrics.calorie-data-change-increase'); - $scope.caloriesUp = true; - $scope.caloriesDown = false; - } else { - $scope.caloriesData.change = $translate.instant('metrics.calorie-data-change-decrease'); - $scope.caloriesUp = false; - $scope.caloriesDown = true; - } + $scope.caloriesData.lastWeekUserCalories = twoWeeksAgoCalories; + console.log("Running calorieData with ", $scope.caloriesData); + // TODO: Refactor this so that we can filter out bad values ahead of time + // instead of having to work around it here + $scope.caloriesData.greaterLesserPct = ($scope.caloriesData.userCalories/$scope.caloriesData.lastWeekUserCalories) * 100 - 100; + } } } $scope.fillCalorieAggVals = function(aggDurationSummaryAvg, aggMedianSpeedSummaryAvg) { + $scope.caloriesData.aggrCalories = 0; for (var i in aggDurationSummaryAvg) { var met = CalorieCal.getMet(aggDurationSummaryAvg[i].key, aggMedianSpeedSummaryAvg[i].values); diff --git a/www/templates/main-metrics.html b/www/templates/main-metrics.html index ebb0a6f73..7fb590358 100644 --- a/www/templates/main-metrics.html +++ b/www/templates/main-metrics.html @@ -116,16 +116,19 @@

{{'.calories'}}

{{'main-metrics.equals-cookies' | translate:{cookies: numberOfCookies}:"messageformat"}}
{{'main-metrics.equals-icecream' | translate:{icecream: numberOfIceCreams}:"messageformat"}}
{{'main-metrics.equals-bananas' | translate:{bananas: numberOfBananas}:"messageformat"}}
-
-
-
-
{{caloriesData.changeInPercentage}}{{caloriesData.change}}
+
+
+
{{ caloriesData.greaterLesserPct | number:0 }}% {{'metrics.greater-than-last-week' | translate }}
+
+
+
+
{{ (-1) * caloriesData.greaterLesserPct | number:0 }}% {{'metrics.less-than-last-week' | translate }}
-
{{'.average'}} {{caloriesData.aggrCalories}}
-
{{'.lastweek'}} {{caloriesData.lastWeekUserCalories}}
+
{{'.average'}} {{caloriesData.aggrCalories}} cal
+
{{'.lastweek'}} {{caloriesData.lastWeekUserCalories}} cal
From c0aa1c9efcdb31b9860a7cd3e3106817066e20dd Mon Sep 17 00:00:00 2001 From: "K. Shankari" Date: Wed, 22 Dec 2021 21:29:10 -0800 Subject: [PATCH 096/175] Remove unused variables --- www/js/metrics.js | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/www/js/metrics.js b/www/js/metrics.js index 3004a4f6e..2a539d602 100644 --- a/www/js/metrics.js +++ b/www/js/metrics.js @@ -18,12 +18,6 @@ angular.module('emission.main.metrics',['nvd3', $translate) { var lastTwoWeeksQuery = true; var defaultTwoWeekUserCall = true; - var lastWeekCalories = 0; - var lastWeekCarbon = "0 kg CO₂"; - var twoWeeksAgoCarbon = ""; - var lastWeekCarbonInt = 0; - var twoWeeksAgoCarbonInt = 0; - var twoWeeksAgoCalories = 0; var DURATION = "duration"; var MEDIAN_SPEED = "median_speed"; @@ -732,6 +726,7 @@ angular.module('emission.main.metrics',['nvd3', if(defaultTwoWeekUserCall) { if (twoWeeksAgoDurationSummary.length > 0) { + var twoWeeksAgoCalories = 0; for (var i in twoWeeksAgoDurationSummary) { var met = $scope.getCorrectedMetFromUserData(twoWeeksAgoDurationSummary[i], twoWeeksAgoMedianSpeedSummary[i]) From dc5d76ba9d17896e26d7b93c58c5ee63a1d9d53b Mon Sep 17 00:00:00 2001 From: "K. Shankari" Date: Wed, 22 Dec 2021 22:20:50 -0800 Subject: [PATCH 097/175] Removed duplicate calls to summarization functions Instead, we pre-compute them all at the beginning. This allows us to avoid recomputing values over and over and improves performance. https://github.com/e-mission/e-mission-docs/issues/688#issuecomment-1000060544 Testing done: Checked the calls using console logs for a regular refresh: ***Current user entries*** ``` Invoked getSummaryDataRaw on Array(5) with duration Invoked getSummaryDataRaw on Array(5) with median_speed Invoked getSummaryDataRaw on Array(5) with count Invoked getSummaryDataRaw on Array(5) with distance ``` ***Two weeks ago entries*** ``` Invoked getSummaryDataRaw on Array(3) with duration Invoked getSummaryDataRaw on Array(3) with median_speed Invoked getSummaryDataRaw on Array(3) with count Invoked getSummaryDataRaw on Array(3) with distance ``` ***Aggregate entries*** ``` Invoked getSummaryDataRaw on Array(8) with duration Invoked getSummaryDataRaw on Array(8) with median_speed Invoked getSummaryDataRaw on Array(8) with count Invoked getSummaryDataRaw on Array(8) with distance ``` ***Current user entries*** ``` Called getDataFromMetrics on Array(6) Called getDataFromMetrics on Array(6) Called getDataFromMetrics on Array(6) Called getDataFromMetrics on Array(6) ``` ***Two weeks ago entries*** ``` Called getDataFromMetrics on Array(7) Called getDataFromMetrics on Array(7) Called getDataFromMetrics on Array(7) Called getDataFromMetrics on Array(7) ``` ***Aggregate entries summary*** ``` Called getDataFromMetrics on Array(13) Called getDataFromMetrics on Array(13) Called getDataFromMetrics on Array(13) Called getDataFromMetrics on Array(13) ``` ***Aggregate entries per capita*** ``` Called getDataFromMetrics on Array(13) Called getDataFromMetrics on Array(13) Called getDataFromMetrics on Array(13) Called getDataFromMetrics on Array(13) ``` --- www/js/metrics.js | 31 +++++++++++++++---------------- 1 file changed, 15 insertions(+), 16 deletions(-) diff --git a/www/js/metrics.js b/www/js/metrics.js index 2a539d602..b8cae8014 100644 --- a/www/js/metrics.js +++ b/www/js/metrics.js @@ -618,7 +618,7 @@ angular.module('emission.main.metrics',['nvd3', $scope.userCurrentSummaryModeMap[m] = getSummaryDataRaw($scope.userCurrentModeMap[m], m)); METRIC_LIST.forEach((m) => - $scope.userTwoWeeksAgoSummaryModeMap[m] = getSummaryDataRaw($scope.userTwoWeeksAgoModeMap[m], metric2valUser)); + $scope.userTwoWeeksAgoSummaryModeMap[m] = getSummaryDataRaw($scope.userTwoWeeksAgoModeMap[m], m)); METRIC_LIST.forEach((m) => $scope.summaryData.userSummary[m] = getSummaryData($scope.userCurrentModeMap[m], m)); @@ -635,7 +635,9 @@ angular.module('emission.main.metrics',['nvd3', $scope.userTwoWeeksAgoSummaryModeMap.duration, $scope.userTwoWeeksAgoSummaryModeMap.median_speed); $scope.fillFootprintCardUserVals($scope.userCurrentModeMap.distance, - $scope.userTwoWeeksAgoModeMap.distance); + $scope.userCurrentSummaryModeMap.distance, + $scope.userTwoWeeksAgoModeMap.distance, + $scope.userTwoWeeksAgoSummaryModeMap.distance); } $scope.fillAggregateValues = function(agg_metrics_arr) { @@ -652,9 +654,6 @@ angular.module('emission.main.metrics',['nvd3', METRIC_LIST.forEach((m) => $scope.aggCurrentModeMapFormatted[m] = formatData($scope.aggCurrentModeMap[m], m)); - METRIC_LIST.forEach((m) => - $scope.aggCurrentSummaryModeMap[m] = getSummaryDataRaw($scope.aggCurrentModeMap[m], m)); - METRIC_LIST.forEach((m) => $scope.aggCurrentPerCapitaModeMap[m] = getDataFromMetrics($scope.aggCurrentResults[m], metric2valAvg)); @@ -771,12 +770,12 @@ angular.module('emission.main.metrics',['nvd3', } }; - $scope.fillFootprintCardUserVals = function(userDistance, twoWeeksAgoDistance) { + $scope.fillFootprintCardUserVals = function( + userDistance, userDistanceSummary, + twoWeeksAgoDistance, twoWeeksAgoDistanceSummary) { if (userDistance) { - var userCarbonData = getSummaryDataRaw(userDistance, 'distance'); - - var optimalDistance = getOptimalFootprintDistance(userDistance); - var worstDistance = getWorstFootprintDistance(userDistance); + // var optimalDistance = getOptimalFootprintDistance(userDistance); + // var worstDistance = getWorstFootprintDistance(userDistance); var date1 = $scope.selectCtrl.fromDateTimestamp; var date2 = $scope.selectCtrl.toDateTimestamp; @@ -793,9 +792,9 @@ angular.module('emission.main.metrics',['nvd3', $scope.carbonData.us2030 = Math.round(54 / 7 * days); // kg/day $scope.carbonData.us2050 = Math.round(14 / 7 * days); - $scope.carbonData.userCarbon = FootprintHelper.getFootprintForMetrics(userCarbonData); - $scope.carbonData.optimalCarbon = FootprintHelper.getLowestFootprintForDistance(optimalDistance); - $scope.carbonData.worstCarbon = FootprintHelper.getHighestFootprintForDistance(worstDistance); + $scope.carbonData.userCarbon = FootprintHelper.getFootprintForMetrics(userDistanceSummary); + // $scope.carbonData.optimalCarbon = FootprintHelper.getLowestFootprintForDistance(optimalDistance); + // $scope.carbonData.worstCarbon = FootprintHelper.getHighestFootprintForDistance(worstDistance); } if (defaultTwoWeekUserCall) { @@ -805,9 +804,7 @@ angular.module('emission.main.metrics',['nvd3', // and this user has been around long enough that they have two weeks // of data, or they haven't turned off tracking for all of last week, // or.... - var userCarbonDataTwoWeeks = getSummaryDataRaw(twoWeeksAgoDistance, 'distance'); - - $scope.carbonData.lastWeekUserCarbon = FootprintHelper.getFootprintForMetrics(userCarbonDataTwoWeeks); + $scope.carbonData.lastWeekUserCarbon = FootprintHelper.getFootprintForMetrics(twoWeeksAgoDistanceSummary); console.log("Running calculation with " + $scope.carbonData.userCarbon + " and " + $scope.carbonData.lastWeekUserCarbon); console.log("Running calculation with ", $scope.carbonData); @@ -873,6 +870,7 @@ angular.module('emission.main.metrics',['nvd3', } var getDataFromMetrics = function(metrics, metric2val) { + console.log("Called getDataFromMetrics on ", metrics); var mode_bins = {}; metrics.forEach(function(metric) { var on_foot_val = 0; @@ -924,6 +922,7 @@ angular.module('emission.main.metrics',['nvd3', } var getSummaryDataRaw = function(modeMap, metric) { + console.log("Invoked getSummaryDataRaw on ", modeMap, "with", metric); let summaryMap = angular.copy(modeMap); for (var i = 0; i < modeMap.length; i++) { var temp = 0; From 3a239e6d8f83159972049daaba672c4d3335af74 Mon Sep 17 00:00:00 2001 From: "K. Shankari" Date: Wed, 22 Dec 2021 22:28:48 -0800 Subject: [PATCH 098/175] Change median_speed to mean_speed Rationale: https://github.com/e-mission/e-mission-docs/issues/688#issuecomment-998466419 Corresponding server change: https://github.com/shankari/e-mission-server/commit/30cb728f790b47964e5234f29e3b4e8716686302 Mean speed is the new speed. Median speed is only supported for backwards compatibility. Testing done: - Loaded the dashboard - Checked the server logs ``` 2021-12-22 22:27:09,051:DEBUG:123145629229056:metric_list = ['duration', 'mean_speed', ' count', 'distance'] ``` --- www/js/metrics.js | 38 +++++++++++++++++++------------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/www/js/metrics.js b/www/js/metrics.js index b8cae8014..99fee59e8 100644 --- a/www/js/metrics.js +++ b/www/js/metrics.js @@ -20,11 +20,11 @@ angular.module('emission.main.metrics',['nvd3', var defaultTwoWeekUserCall = true; var DURATION = "duration"; - var MEDIAN_SPEED = "median_speed"; + var MEAN_SPEED = "mean_speed"; var COUNT = "count"; var DISTANCE = "distance"; - var METRIC_LIST = [DURATION, MEDIAN_SPEED, COUNT, DISTANCE]; + var METRIC_LIST = [DURATION, MEAN_SPEED, COUNT, DISTANCE]; /* * BEGIN: Data structures to parse and store the data in different formats. @@ -43,7 +43,7 @@ angular.module('emission.main.metrics',['nvd3', ts: 1638489600},....], duration: [...] distance: [...] - median_speed: [...]} + mean_speed: [...]} */ $scope.userCurrentResults = {}; $scope.userTwoWeeksAgo = {}; @@ -61,7 +61,7 @@ angular.module('emission.main.metrics',['nvd3', { key: walk, values: [[1638489600, 4, "2021-12-03T00:00:00+00:00"],...]}], duration: [ { key: drove_alone, values: [...]}, {key: walk, values: [...]} ], distance: [ { key: drove_alone, values: [...]}, {key: walk, values: [...]} ], - median_speed: [ { key: drove_alone, values: [...]}, {key: walk, values: [...]} ] + mean_speed: [ { key: drove_alone, values: [...]}, {key: walk, values: [...]} ] } */ $scope.userCurrentModeMap = {}; @@ -81,7 +81,7 @@ angular.module('emission.main.metrics',['nvd3', duration: [ { key: drove_alone, values: [...]}, {key: walk, values: [...]} ], distance: [ { key: drove_alone, values: [...]}, {key: walk, values: [...]} ], - median_speed: [ { key: drove_alone, values: [...]}, {key: walk, values: [...]} ] + mean_speed: [ { key: drove_alone, values: [...]}, {key: walk, values: [...]} ] } */ $scope.userCurrentSummaryModeMap = {}; @@ -631,9 +631,9 @@ angular.module('emission.main.metrics',['nvd3', // Fill in user calorie information $scope.fillCalorieCardUserVals($scope.userCurrentSummaryModeMap.duration, - $scope.userCurrentSummaryModeMap.median_speed, + $scope.userCurrentSummaryModeMap.mean_speed, $scope.userTwoWeeksAgoSummaryModeMap.duration, - $scope.userTwoWeeksAgoSummaryModeMap.median_speed); + $scope.userTwoWeeksAgoSummaryModeMap.mean_speed); $scope.fillFootprintCardUserVals($scope.userCurrentModeMap.distance, $scope.userCurrentSummaryModeMap.distance, $scope.userTwoWeeksAgoModeMap.distance, @@ -662,7 +662,7 @@ angular.module('emission.main.metrics',['nvd3', $scope.chartDataAggr = $scope.aggCurrentModeMapFormatted; $scope.fillCalorieAggVals($scope.aggCurrentSummaryPerCapitaModeMap.duration, - $scope.aggCurrentSummaryPerCapitaModeMap.median_speed); + $scope.aggCurrentSummaryPerCapitaModeMap.mean_speed); $scope.fillFootprintAggVals($scope.aggCurrentSummaryPerCapitaModeMap.distance); } @@ -708,10 +708,10 @@ angular.module('emission.main.metrics',['nvd3', return undefined; } - $scope.fillCalorieCardUserVals = function(userDurationSummary, userMedianSpeedSummary, - twoWeeksAgoDurationSummary, twoWeeksAgoMedianSpeedSummary) { + $scope.fillCalorieCardUserVals = function(userDurationSummary, userMeanSpeedSummary, + twoWeeksAgoDurationSummary, twoWeeksAgoMeanSpeedSummary) { for (var i in userDurationSummary) { - var met = $scope.getCorrectedMetFromUserData(userDurationSummary[i], userMedianSpeedSummary[i]) + var met = $scope.getCorrectedMetFromUserData(userDurationSummary[i], userMeanSpeedSummary[i]) $scope.caloriesData.userCalories += Math.round(CalorieCal.getuserCalories(userDurationSummary[i].values / 3600, met)) //+ ' cal' } @@ -728,7 +728,7 @@ angular.module('emission.main.metrics',['nvd3', var twoWeeksAgoCalories = 0; for (var i in twoWeeksAgoDurationSummary) { var met = $scope.getCorrectedMetFromUserData(twoWeeksAgoDurationSummary[i], - twoWeeksAgoMedianSpeedSummary[i]) + twoWeeksAgoMeanSpeedSummary[i]) twoWeeksAgoCalories += Math.round(CalorieCal.getuserCalories(twoWeeksAgoDurationSummary[i].values / 3600, met)); } @@ -741,11 +741,11 @@ angular.module('emission.main.metrics',['nvd3', } } - $scope.fillCalorieAggVals = function(aggDurationSummaryAvg, aggMedianSpeedSummaryAvg) { + $scope.fillCalorieAggVals = function(aggDurationSummaryAvg, aggMeanSpeedSummaryAvg) { $scope.caloriesData.aggrCalories = 0; for (var i in aggDurationSummaryAvg) { - var met = CalorieCal.getMet(aggDurationSummaryAvg[i].key, aggMedianSpeedSummaryAvg[i].values); + var met = CalorieCal.getMet(aggDurationSummaryAvg[i].key, aggMeanSpeedSummaryAvg[i].values); $scope.caloriesData.aggrCalories += Math.round(CalorieCal.getuserCalories(aggDurationSummaryAvg[i].values / 3600, met)) //+ ' cal' @@ -929,7 +929,7 @@ angular.module('emission.main.metrics',['nvd3', for (var j = 0; j < modeMap[i].values.length; j++) { temp += modeMap[i].values[j][1]; } - if (metric === "median_speed") { + if (metric === "mean_speed") { summaryMap[i].values = Math.round(temp / modeMap[i].values.length); } else { summaryMap[i].values = Math.round(temp); @@ -983,7 +983,7 @@ angular.module('emission.main.metrics',['nvd3', // we pick hours as a reasonable formatted metric unit = $translate.instant('metrics.hours'); break; - case "median_speed": + case "mean_speed": unit = ImperialConfig.getSpeedSuffix; break; } @@ -994,7 +994,7 @@ angular.module('emission.main.metrics',['nvd3', let formattedModeStatList = angular.copy(modeStatList); formattedModeStatList.forEach((modeStat) => { var stringRep = ""; - if (metric === "median_speed") { + if (metric === "mean_speed") { let spdStr = ImperialConfig.getFormattedSpeed( modeStat[1]); modeStat[1] = Number.parseFloat(spdStr); stringRep = spdStr + " " + unit; @@ -1036,11 +1036,11 @@ angular.module('emission.main.metrics',['nvd3', case "duration": unit = "s"; break; - case "median_speed": + case "mean_speed": unit = "m/s"; break; } - if (metric === "median_speed") { + if (metric === "mean_speed") { summaryData[i].values = ImperialConfig.getFormattedSpeed(temp / summaryData[i].values.length ) + ' ' + ImperialConfig.getSpeedSuffix; } else if(metric === "distance"){ summaryData[i].values = ImperialConfig.getFormattedDistance(temp) + ' ' + ImperialConfig.getDistanceSuffix; From ddececdf4b6f1767b6b2f6be3038605c73662ace Mon Sep 17 00:00:00 2001 From: "K. Shankari" Date: Thu, 23 Dec 2021 06:23:12 -0800 Subject: [PATCH 099/175] Pre-compute values needed for computation only As part of the performance reorg, we pre-compute all values. However, some of these values are not used for either computation or display. - user current values are used for display in the summary and the charts - aggregate current total values are used for display in the charts - two weeks ago values are only used for computation - aggregate per capita values are only used for computation We don't use count in the computation, so let's not include it in the precomputated values that are only used for computation (two weeks ago, aggregate) --- www/js/metrics.js | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/www/js/metrics.js b/www/js/metrics.js index 99fee59e8..913707fc1 100644 --- a/www/js/metrics.js +++ b/www/js/metrics.js @@ -25,6 +25,7 @@ angular.module('emission.main.metrics',['nvd3', var DISTANCE = "distance"; var METRIC_LIST = [DURATION, MEAN_SPEED, COUNT, DISTANCE]; + var COMPUTATIONAL_METRIC_LIST = [DURATION, MEAN_SPEED, DISTANCE]; /* * BEGIN: Data structures to parse and store the data in different formats. @@ -608,7 +609,7 @@ angular.module('emission.main.metrics',['nvd3', METRIC_LIST.forEach((m) => $scope.userCurrentModeMap[m] = getDataFromMetrics($scope.userCurrentResults[m], metric2valUser)); - METRIC_LIST.forEach((m) => + COMPUTATIONAL_METRIC_LIST.forEach((m) => $scope.userTwoWeeksAgoModeMap[m] = getDataFromMetrics($scope.userTwoWeeksAgo[m], metric2valUser)); METRIC_LIST.forEach((m) => @@ -617,7 +618,7 @@ angular.module('emission.main.metrics',['nvd3', METRIC_LIST.forEach((m) => $scope.userCurrentSummaryModeMap[m] = getSummaryDataRaw($scope.userCurrentModeMap[m], m)); - METRIC_LIST.forEach((m) => + COMPUTATIONAL_METRIC_LIST.forEach((m) => $scope.userTwoWeeksAgoSummaryModeMap[m] = getSummaryDataRaw($scope.userTwoWeeksAgoModeMap[m], m)); METRIC_LIST.forEach((m) => @@ -654,10 +655,10 @@ angular.module('emission.main.metrics',['nvd3', METRIC_LIST.forEach((m) => $scope.aggCurrentModeMapFormatted[m] = formatData($scope.aggCurrentModeMap[m], m)); - METRIC_LIST.forEach((m) => + COMPUTATIONAL_METRIC_LIST.forEach((m) => $scope.aggCurrentPerCapitaModeMap[m] = getDataFromMetrics($scope.aggCurrentResults[m], metric2valAvg)); - METRIC_LIST.forEach((m) => + COMPUTATIONAL_METRIC_LIST.forEach((m) => $scope.aggCurrentSummaryPerCapitaModeMap[m] = getSummaryDataRaw($scope.aggCurrentPerCapitaModeMap[m], m)); $scope.chartDataAggr = $scope.aggCurrentModeMapFormatted; From 98af95d9b1965d35a3f0434670057fe2fe1eca4b Mon Sep 17 00:00:00 2001 From: "K. Shankari" Date: Thu, 23 Dec 2021 08:23:43 -0800 Subject: [PATCH 100/175] Refactor `formatData` to a set of formatters that can be reused We need to format both the chart data and the summary data, but the summary card wants one value per mode while the charts want multiple values per mode. So the format code needs to work on an array in one case and on individual values in the other. So we pull out the formatters such that they work on one value at a time, which will also simplify the giant bolus of code that is the formatXXX/getSummaryData. We can then call the formatters as the inner value in the loop, or maybe even call it directly from the HTML https://github.com/e-mission/e-mission-docs/issues/688#issuecomment-1000356833 --- www/js/config/imperial.js | 6 +-- www/js/metrics.js | 86 +++++++++++++++++++++------------------ 2 files changed, 49 insertions(+), 43 deletions(-) diff --git a/www/js/config/imperial.js b/www/js/config/imperial.js index 7c3f4c560..1503bfa62 100644 --- a/www/js/config/imperial.js +++ b/www/js/config/imperial.js @@ -15,14 +15,14 @@ angular.module('emission.config.imperial', ['emission.plugin.logger']) ic.getFormattedDistanceInKm = function(dist_in_meters) { if (dist_in_meters > 1000) { - return (dist_in_meters/1000).toFixed(0); + return Number.parseFloat((dist_in_meters/1000).toFixed(0)); } else { - return (dist_in_meters/1000).toFixed(3); + return Number.parseFloat((dist_in_meters/1000).toFixed(3)); } } ic.getFormattedDistanceInMiles = function(dist_in_meters) { - return (KM_TO_MILES * ic.getFormattedDistanceInKm(dist_in_meters)).toFixed(1); + return Number.parseFloat((KM_TO_MILES * ic.getFormattedDistanceInKm(dist_in_meters)).toFixed(1)); } ic.getKmph = function(metersPerSec) { diff --git a/www/js/metrics.js b/www/js/metrics.js index 913707fc1..9f0177bee 100644 --- a/www/js/metrics.js +++ b/www/js/metrics.js @@ -613,7 +613,7 @@ angular.module('emission.main.metrics',['nvd3', $scope.userTwoWeeksAgoModeMap[m] = getDataFromMetrics($scope.userTwoWeeksAgo[m], metric2valUser)); METRIC_LIST.forEach((m) => - $scope.userCurrentModeMapFormatted[m] = formatData($scope.userCurrentModeMap[m], m)); + $scope.userCurrentModeMapFormatted[m] = formatModeMap($scope.userCurrentModeMap[m], m)); METRIC_LIST.forEach((m) => $scope.userCurrentSummaryModeMap[m] = getSummaryDataRaw($scope.userCurrentModeMap[m], m)); @@ -653,7 +653,7 @@ angular.module('emission.main.metrics',['nvd3', $scope.aggCurrentModeMap[m] = getDataFromMetrics($scope.aggCurrentResults[m], metric2valUser)); METRIC_LIST.forEach((m) => - $scope.aggCurrentModeMapFormatted[m] = formatData($scope.aggCurrentModeMap[m], m)); + $scope.aggCurrentModeMapFormatted[m] = formatModeMap($scope.aggCurrentModeMap[m], m)); COMPUTATIONAL_METRIC_LIST.forEach((m) => $scope.aggCurrentPerCapitaModeMap[m] = getDataFromMetrics($scope.aggCurrentResults[m], metric2valAvg)); @@ -971,48 +971,54 @@ angular.module('emission.main.metrics',['nvd3', return distance; } - var formatData = function(modeMapList, metric) { - var unit = ""; - switch(metric) { - case "count": - unit = $translate.instant('metrics.trips'); - break; - case "distance": - unit = ImperialConfig.getDistanceSuffix; - break; - case "duration": - // we pick hours as a reasonable formatted metric - unit = $translate.instant('metrics.hours'); - break; - case "mean_speed": - unit = ImperialConfig.getSpeedSuffix; - break; - } + $scope.formatCount = function(value) { + const formatVal = Math.round(value); + const unit = $translate.instant('metrics.trips'); + const stringRep = formatVal + " " + unit; + return [formatVal, unit, stringRep]; + } + + $scope.formatDistance = function(value) { + const formatVal = Number.parseFloat(ImperialConfig.getFormattedDistance(value)); + const unit = ImperialConfig.getDistanceSuffix; + const stringRep = formatVal + " " + unit; + return [formatVal, unit, stringRep]; + } + + $scope.formatDuration = function(value) { + const durM = moment.duration(value * 1000); + const formatVal = durM.asHours(); + const unit = $translate.instant('metrics.hours'); + const stringRep = durM.humanize(); + return [formatVal, unit, stringRep]; + } + + $scope.formatMeanSpeed = function(value) { + const formatVal = Number.parseFloat(ImperialConfig.getFormattedSpeed(value)); + const unit = ImperialConfig.getSpeedSuffix; + const stringRep = formatVal + " " + unit; + return [formatVal, unit, stringRep]; + } + + $scope.formatterMap = { + count: $scope.formatCount, + distance: $scope.formatDistance, + duration: $scope.formatDuration, + mean_speed: $scope.formatMeanSpeed + } + + var formatModeMap = function(modeMapList, metric) { + const formatter = $scope.formatterMap[metric]; let formattedModeList = []; modeMapList.forEach((modeMap) => { let currMode = modeMap["key"]; let modeStatList = modeMap["values"]; - let formattedModeStatList = angular.copy(modeStatList); - formattedModeStatList.forEach((modeStat) => { - var stringRep = ""; - if (metric === "mean_speed") { - let spdStr = ImperialConfig.getFormattedSpeed( modeStat[1]); - modeStat[1] = Number.parseFloat(spdStr); - stringRep = spdStr + " " + unit; - } else if(metric === "distance"){ - let distStr = ImperialConfig.getFormattedDistance(modeStat[1]); - modeStat[1] = Number.parseFloat(distStr); - stringRep = distStr + " " + unit; - } else if(metric === "duration"){ - let durM = moment.duration(modeStat[1] * 1000); - modeStat[1] = durM.asHours().toFixed(2); - stringRep = durM.humanize(); - } else { - modeStat[1] = Math.round(modeStat[1]); - stringRep = modeStat[1] + " " + unit; - } - modeStat.push(unit); - modeStat.push(stringRep); + let formattedModeStatList = modeStatList.map((modeStat) => { + let [formatVal, unit, stringRep] = formatter(modeStat[1]); + let copiedModeStat = angular.copy(modeStat); + copiedModeStat[1] = formatVal; + copiedModeStat.push(unit); + copiedModeStat.push(stringRep); }); formattedModeList.push({key: currMode, values: formattedModeStatList}); }); From a8b5f6548af547c2a8860d7d07e68cf2999dcafc Mon Sep 17 00:00:00 2001 From: "K. Shankari" Date: Thu, 23 Dec 2021 08:39:00 -0800 Subject: [PATCH 101/175] Call the formatters directly from the HTML for the numeric summary tab Now that we have specific formatters, we can just call them directly from the HTML and don't have to pre-compute. And obviously, the easiest way to do this is to format the precomputed summaries. So it turns out that we do implement the second option from https://github.com/e-mission/e-mission-docs/issues/688#issuecomment-1000356833 after all, just directly from the HTML!! --- www/js/metrics.js | 2 +- www/templates/main-metrics.html | 20 ++++++++++---------- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/www/js/metrics.js b/www/js/metrics.js index 9f0177bee..048daf0cf 100644 --- a/www/js/metrics.js +++ b/www/js/metrics.js @@ -622,7 +622,7 @@ angular.module('emission.main.metrics',['nvd3', $scope.userTwoWeeksAgoSummaryModeMap[m] = getSummaryDataRaw($scope.userTwoWeeksAgoModeMap[m], m)); METRIC_LIST.forEach((m) => - $scope.summaryData.userSummary[m] = getSummaryData($scope.userCurrentModeMap[m], m)); + $scope.summaryData.userSummary[m] = getSummaryDataRaw($scope.userCurrentModeMap[m], m)); $scope.isCustomLabelResult = isCustomLabels($scope.userCurrentModeMap); FootprintHelper.setUseCustomFootprint($scope.isCustomLabelResult); diff --git a/www/templates/main-metrics.html b/www/templates/main-metrics.html index 7fb590358..466a5302f 100644 --- a/www/templates/main-metrics.html +++ b/www/templates/main-metrics.html @@ -161,7 +161,7 @@

{{'.distance'}}

{{ summaryData.defaultSummary.distance[dIndex + i].key }}
- {{ summaryData.defaultSummary.distance[dIndex + i].values }} + {{ formatDistance(summaryData.defaultSummary.distance[dIndex + i].values).slice(-1)[0] }}
@@ -183,7 +183,7 @@

{{'.trips'}}

{{ summaryData.defaultSummary.count[dIndex + i].key }}
- {{ summaryData.defaultSummary.count[dIndex + i].values }} + {{ formatCount(summaryData.defaultSummary.count[dIndex + i].values).slice(-1)[0] }}
@@ -205,7 +205,7 @@

{{'.duration'}}

{{ summaryData.defaultSummary.duration[dIndex + i].key }}
- {{ summaryData.defaultSummary.duration[dIndex + i].values }} + {{ formatDuration(summaryData.defaultSummary.duration[dIndex + i].values).slice(-1)[0] }}
@@ -214,20 +214,20 @@

{{'.duration'}}

-

{{'.median-speed'}}

-
{{'.no-summary-data'}}
-
-
+

{{'.mean-speed'}}

+
{{'.no-summary-data'}}
+
+
- +
- {{ summaryData.defaultSummary.median_speed[dIndex + i].key }} + {{ summaryData.defaultSummary.mean_speed[dIndex + i].key }}
- {{ summaryData.defaultSummary.median_speed[dIndex + i].values }} + {{ formatMeanSpeed(summaryData.defaultSummary.mean_speed[dIndex + i].values).slice(-1)[0] }}
From d0bdc9ac57d06a1c4f9dced65811560691d4933f Mon Sep 17 00:00:00 2001 From: "K. Shankari" Date: Thu, 23 Dec 2021 08:55:03 -0800 Subject: [PATCH 102/175] Minor fixes to the charts - Return the copiedModeStat from the `map` function in `formatModeMap` code so that we don't end up with multiple `undefined` entries. Fix for 98af95d9b1965d35a3f0434670057fe2fe1eca4b - Use `mean_speed` instead of `median_speed`. Fix for 3a239e6d8f83159972049daaba672c4d3335af74 --- www/js/metrics.js | 1 + www/templates/main-metrics.html | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/www/js/metrics.js b/www/js/metrics.js index 048daf0cf..5b95b0b87 100644 --- a/www/js/metrics.js +++ b/www/js/metrics.js @@ -1019,6 +1019,7 @@ angular.module('emission.main.metrics',['nvd3', copiedModeStat[1] = formatVal; copiedModeStat.push(unit); copiedModeStat.push(stringRep); + return copiedModeStat; }); formattedModeList.push({key: currMode, values: formattedModeStatList}); }); diff --git a/www/templates/main-metrics.html b/www/templates/main-metrics.html index 466a5302f..94a820cbc 100644 --- a/www/templates/main-metrics.html +++ b/www/templates/main-metrics.html @@ -49,7 +49,7 @@ - +
From 2c419232812292a77a8b3a423a472c9300264cee Mon Sep 17 00:00:00 2001 From: "K. Shankari" Date: Thu, 23 Dec 2021 09:53:01 -0800 Subject: [PATCH 103/175] Minor fix to the summary Use `mean_speed` instead of `median_speed` Fix for 3a239e6d8f83159972049daaba672c4d3335af74, similar to d0bdc9ac57d06a1c4f9dced65811560691d4933f --- www/i18n/en.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/www/i18n/en.json b/www/i18n/en.json index a68969a35..cdad3a50c 100644 --- a/www/i18n/en.json +++ b/www/i18n/en.json @@ -226,7 +226,7 @@ "calories": "Calories", "calibrate": "Calibrate", "no-summary-data": "No summary data", - "median-speed": "Median Speed", + "mean-speed": "Average Speed", "equals-cookies": "Equals {cookies, plural, =0{0 homemade chocolate chip cookies} one {1 homemade chocolate chip cookie} other {# homemade chocolate chip cookies}}", "equals-icecream": "Equals {icecream, plural, =0{0 half cups vanilla ice cream} one {1 half cup vanilla ice cream} other {# half cups vanilla ice cream}}", "equals-bananas": "Equals {bananas, plural, =0{0 bananas} one {1 banana} other {# bananas}}" From 41b858f5701124c218ad774cbb1dd71aadf86240 Mon Sep 17 00:00:00 2001 From: "K. Shankari" Date: Thu, 23 Dec 2021 09:54:14 -0800 Subject: [PATCH 104/175] Finally remove ugly and hacky `getSummaryData` Now that we have implemented 98af95d9b1965d35a3f0434670057fe2fe1eca4b and a8b5f6548af547c2a8860d7d07e68cf2999dcafc --- www/js/metrics.js | 36 ------------------------------------ 1 file changed, 36 deletions(-) diff --git a/www/js/metrics.js b/www/js/metrics.js index 5b95b0b87..810570efc 100644 --- a/www/js/metrics.js +++ b/www/js/metrics.js @@ -1026,42 +1026,6 @@ angular.module('emission.main.metrics',['nvd3', return formattedModeList; } - var getSummaryData = function(modeMap, metric) { - var summaryData = angular.copy(modeMap); - for (var i = 0; i < summaryData.length; i++) { - var temp = 0; - for (var j = 0; j < summaryData[i].values.length; j++) { - temp += summaryData[i].values[j][1]; - } - var unit = ""; - switch(metric) { - case "count": - unit = $translate.instant('metrics.trips'); - break; - case "distance": - unit = "m"; - break; - case "duration": - unit = "s"; - break; - case "mean_speed": - unit = "m/s"; - break; - } - if (metric === "mean_speed") { - summaryData[i].values = ImperialConfig.getFormattedSpeed(temp / summaryData[i].values.length ) + ' ' + ImperialConfig.getSpeedSuffix; - } else if(metric === "distance"){ - summaryData[i].values = ImperialConfig.getFormattedDistance(temp) + ' ' + ImperialConfig.getDistanceSuffix; - } else if(metric === "duration" && temp > 60){ - summaryData[i].values = moment.duration(temp * 1000).humanize(); - } else { - summaryData[i].values = Math.round(temp) + ' ' + $translate.instant('metrics.trips'); - } - - } - return summaryData; - } - $scope.changeFromWeekday = function() { return $scope.changeWeekday(function(newVal) { $scope.selectCtrl.fromDateWeekdayString = newVal; From a4caeb312a4ca49439198e8e98d64dbb9c0bb634 Mon Sep 17 00:00:00 2001 From: "K. Shankari" Date: Thu, 23 Dec 2021 10:37:24 -0800 Subject: [PATCH 105/175] Disable the "filter" option from the date selection This is because - they don't actually work for the goals since we cannot figure out the number of days - they are confusing for users since most people who selected Nov 10 to Dec 11, would not expect only 1 day's worth of data - they make it so that we can't display the current range on the summary page https://github.com/e-mission/e-mission-docs/issues/688#issuecomment-1000460939 The changes are fairly simple: - disable the range v/s filter selection in the HTML since without filter, there's no point in having just the range. - Change the CSS of the 'current' code so that it is 100% of the width, with a green background and center align. Since if we don't have the selection, we may as well have the title go the entire way across --- www/css/style.css | 8 ++++++++ www/templates/metrics/metrics-control.html | 8 +++++++- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/www/css/style.css b/www/css/style.css index dee871077..d76848d38 100644 --- a/www/css/style.css +++ b/www/css/style.css @@ -1379,6 +1379,14 @@ span.rz-bar-wrapper { width: 28%; height: 35px; } +.metric-current-title-nofilter { + position: absolute; + color: white; + background-color: #01D0A7; + text-align: center; + width: 100%; + height: 35px; +} .metric-range-button { border-left-color: #ccc; border-left-style: solid; diff --git a/www/templates/metrics/metrics-control.html b/www/templates/metrics/metrics-control.html index b80568915..c8c0f342e 100644 --- a/www/templates/metrics/metrics-control.html +++ b/www/templates/metrics/metrics-control.html @@ -6,9 +6,12 @@
-
{{ uictrl.currentString }}
+
{{ uictrl.currentString }}
+
@@ -47,6 +50,8 @@
+ From fc97329ffd73498cb15bc140f595b007a8d38c34 Mon Sep 17 00:00:00 2001 From: "K. Shankari" Date: Thu, 23 Dec 2021 11:35:08 -0800 Subject: [PATCH 106/175] Improve the date range stuff now that we don't have to worry about filters - Display the date range in the summary screen so people know what they expect - Format the selector using locale-specific formatting so everybody can be happy To display the date range: - we ensure that the "change date" button is always 50% (regardless of chart or summary) - display the date range on right in the summary - display the "self v/s group" on right in the charts --- www/js/metrics.js | 13 ++++++++++--- www/templates/main-metrics.html | 8 +++++--- www/templates/metrics/metrics-control.html | 4 ++-- 3 files changed, 17 insertions(+), 8 deletions(-) diff --git a/www/js/metrics.js b/www/js/metrics.js index 810570efc..95053fd2b 100644 --- a/www/js/metrics.js +++ b/www/js/metrics.js @@ -1217,8 +1217,10 @@ angular.module('emission.main.metrics',['nvd3', $scope.setCurDayFrom = function(val) { if (val) { $scope.selectCtrl.fromDateTimestamp = moment(val).utc(); + $scope.datepickerObjFrom.inputMoment = $scope.selectCtrl.fromDateTimestamp; $scope.datepickerObjFrom.inputDate = $scope.selectCtrl.fromDateTimestamp.toDate(); } else { + $scope.datepickerObjFrom.inputMoment = $scope.selectCtrl.fromDateTimestamp; $scope.datepickerObjFrom.inputDate = $scope.selectCtrl.fromDateTimestamp.toDate(); } @@ -1226,11 +1228,12 @@ angular.module('emission.main.metrics',['nvd3', $scope.setCurDayTo = function(val) { if (val) { $scope.selectCtrl.toDateTimestamp = moment(val).utc(); + $scope.datepickerObjTo.inputMoment = $scope.selectCtrl.toDateTimestamp; $scope.datepickerObjTo.inputDate = $scope.selectCtrl.toDateTimestamp.toDate(); } else { + $scope.datepickerObjTo.inputMoment = $scope.selectCtrl.toDateTimestamp; $scope.datepickerObjTo.inputDate = $scope.selectCtrl.toDateTimestamp.toDate(); } - }; @@ -1263,9 +1266,12 @@ angular.module('emission.main.metrics',['nvd3', ] }); } + + $scope.localDateFormat = moment.localeData().longDateFormat('ll'); $scope.datepickerObjFrom = { callback: $scope.setCurDayFrom, inputDate: $scope.selectCtrl.fromDateTimestamp.toDate(), + inputMoment: $scope.selectCtrl.fromDateTimestamp, todayLabel: $translate.instant('list-datepicker-today'), //Optional closeLabel: $translate.instant('list-datepicker-close'), //Optional setLabel: $translate.instant('list-datepicker-set'), //Optional @@ -1277,13 +1283,14 @@ angular.module('emission.main.metrics',['nvd3', from: new Date(2015, 1, 1), to: new Date(), showTodayButton: true, - dateFormat: 'dd/MM/yyyy', + dateFormat: $scope.localDateFormat, closeOnSelect: false, // add this instruction if you want to exclude a particular weekday, e.g. Saturday disableWeekdays: [6] }; $scope.datepickerObjTo = { callback: $scope.setCurDayTo, inputDate: $scope.selectCtrl.toDateTimestamp.toDate(), + inputMoment: $scope.selectCtrl.toDateTimestamp, todayLabel: $translate.instant('list-datepicker-today'), //Optional closeLabel: $translate.instant('list-datepicker-close'), //Optional setLabel: $translate.instant('list-datepicker-set'), //Optional @@ -1295,7 +1302,7 @@ angular.module('emission.main.metrics',['nvd3', from: new Date(2015, 1, 1), to: new Date(), showTodayButton: true, - dateFormat: 'dd/MM/yyyy', + dateFormat: $scope.localDateFormat, closeOnSelect: false, // add this instruction if you want to exclude a particular weekday, e.g. Saturday disableWeekdays: [6] }; diff --git a/www/templates/main-metrics.html b/www/templates/main-metrics.html index 94a820cbc..4329eb735 100644 --- a/www/templates/main-metrics.html +++ b/www/templates/main-metrics.html @@ -18,11 +18,13 @@
{{'.chart'}}
-
+
{{'.change-data'}}
-
-
{{'.change-data'}}
+
+
+
{{ selectCtrl.fromDateTimestamp.format('ll') }} ➡️ {{ selectCtrl.toDateTimestamp.format('ll') }}
+
diff --git a/www/templates/metrics/metrics-control.html b/www/templates/metrics/metrics-control.html index c8c0f342e..2953e39d1 100644 --- a/www/templates/metrics/metrics-control.html +++ b/www/templates/metrics/metrics-control.html @@ -22,7 +22,7 @@
@@ -37,7 +37,7 @@
From c5eaeb1b7e400f94126434ae7fce17d8538c25f5 Mon Sep 17 00:00:00 2001 From: "K. Shankari" Date: Thu, 23 Dec 2021 15:38:36 -0800 Subject: [PATCH 107/175] Unify the datepicker settings to avoid code duplication Create a base object with the majority of the settings, and then create two copies by cloning and extend to create the from and to datepickers + remove the dateFormat in the config since it is not used --- www/js/metrics.js | 34 ++++++++++++---------------------- 1 file changed, 12 insertions(+), 22 deletions(-) diff --git a/www/js/metrics.js b/www/js/metrics.js index 95053fd2b..7612ca00e 100644 --- a/www/js/metrics.js +++ b/www/js/metrics.js @@ -1267,11 +1267,7 @@ angular.module('emission.main.metrics',['nvd3', }); } - $scope.localDateFormat = moment.localeData().longDateFormat('ll'); - $scope.datepickerObjFrom = { - callback: $scope.setCurDayFrom, - inputDate: $scope.selectCtrl.fromDateTimestamp.toDate(), - inputMoment: $scope.selectCtrl.fromDateTimestamp, + $scope.datepickerObjBase = { todayLabel: $translate.instant('list-datepicker-today'), //Optional closeLabel: $translate.instant('list-datepicker-close'), //Optional setLabel: $translate.instant('list-datepicker-set'), //Optional @@ -1283,29 +1279,23 @@ angular.module('emission.main.metrics',['nvd3', from: new Date(2015, 1, 1), to: new Date(), showTodayButton: true, - dateFormat: $scope.localDateFormat, closeOnSelect: false, // add this instruction if you want to exclude a particular weekday, e.g. Saturday disableWeekdays: [6] }; - $scope.datepickerObjTo = { + + $scope.datepickerObjFrom = angular.copy($scope.datepickerObjBase); + angular.extend($scope.datepickerObjFrom, { + callback: $scope.setCurDayFrom, + inputDate: $scope.selectCtrl.fromDateTimestamp.toDate(), + inputMoment: $scope.selectCtrl.fromDateTimestamp, + }); + + $scope.datepickerObjTo = angular.copy($scope.datepickerObjBase); + angular.extend($scope.datepickerObjTo, { callback: $scope.setCurDayTo, inputDate: $scope.selectCtrl.toDateTimestamp.toDate(), inputMoment: $scope.selectCtrl.toDateTimestamp, - todayLabel: $translate.instant('list-datepicker-today'), //Optional - closeLabel: $translate.instant('list-datepicker-close'), //Optional - setLabel: $translate.instant('list-datepicker-set'), //Optional - titleLabel: $translate.instant('metrics.pick-a-date'), - mondayFirst: false, - weeksList: moment.weekdaysMin(), - monthsList: moment.monthsShort(), - templateType: 'popup', - from: new Date(2015, 1, 1), - to: new Date(), - showTodayButton: true, - dateFormat: $scope.localDateFormat, - closeOnSelect: false, - // add this instruction if you want to exclude a particular weekday, e.g. Saturday disableWeekdays: [6] - }; + }); $scope.pickFromDay = function() { ionicDatePicker.openDatePicker($scope.datepickerObjFrom); From e3116356dc9dddb39ba0c926c5d099c7672243a2 Mon Sep 17 00:00:00 2001 From: "K. Shankari" Date: Thu, 23 Dec 2021 16:37:08 -0800 Subject: [PATCH 108/175] Re-enable the "worst" comparison This was actually fairly straightforward, since we just multiply the entire distance by the worst footprint. The main changes were: - we can pass in the summary directly instead of recreating the mode map + summary - we can simplify the max footprint detection - clarify the text some more --- www/i18n/en.json | 4 ++-- www/js/metrics-factory.js | 5 +++-- www/js/metrics.js | 17 +++++------------ www/templates/main-metrics.html | 4 +--- 4 files changed, 11 insertions(+), 19 deletions(-) diff --git a/www/i18n/en.json b/www/i18n/en.json index cdad3a50c..16830df72 100644 --- a/www/i18n/en.json +++ b/www/i18n/en.json @@ -217,9 +217,9 @@ "speed": "Speed", "footprint": "My Footprint", "how-it-compares": "Ballpark comparisons", - "optimal": "Optimal for my trips:", + "optimal": "Optimal for my trips (perfect mode choice):", "average": "Average for group:", - "worst": "Worst for my trips:", + "worst": "Worst for my trips (drive everywhere):", "lastweek": "My last week value:", "us-2030-goal": "US 2030 Goal Estimate:", "us-2050-goal": "US 2050 Goal Estimate:", diff --git a/www/js/metrics-factory.js b/www/js/metrics-factory.js index 63ebe9066..b21845825 100644 --- a/www/js/metrics-factory.js +++ b/www/js/metrics-factory.js @@ -61,10 +61,11 @@ angular.module('emission.main.metrics.factory', } fh.getHighestFootprintForDistance = function(distance) { var footprint = fh.getFootprint(); - var highestFootprint = 0; + let footprintList = []; for (var mode in footprint) { - highestFootprint = Math.max(highestFootprint, footprint[mode]); + footprintList.push(footprint[mode]); } + const highestFootprint = Math.max(...footprintList); return highestFootprint * mtokm(distance); } diff --git a/www/js/metrics.js b/www/js/metrics.js index 7612ca00e..b0356c441 100644 --- a/www/js/metrics.js +++ b/www/js/metrics.js @@ -518,7 +518,6 @@ angular.module('emission.main.metrics',['nvd3', $scope.carbonData.userCarbon = 0; $scope.carbonData.optimalCarbon = "0 kg CO₂"; - $scope.carbonData.worstCarbon = "0 kg CO₂"; $scope.summaryData.userSummary = []; $scope.chartDataUser = {}; @@ -776,7 +775,7 @@ angular.module('emission.main.metrics',['nvd3', twoWeeksAgoDistance, twoWeeksAgoDistanceSummary) { if (userDistance) { // var optimalDistance = getOptimalFootprintDistance(userDistance); - // var worstDistance = getWorstFootprintDistance(userDistance); + var worstDistance = getWorstFootprintDistance(userDistanceSummary); var date1 = $scope.selectCtrl.fromDateTimestamp; var date2 = $scope.selectCtrl.toDateTimestamp; @@ -795,7 +794,7 @@ angular.module('emission.main.metrics',['nvd3', $scope.carbonData.userCarbon = FootprintHelper.getFootprintForMetrics(userDistanceSummary); // $scope.carbonData.optimalCarbon = FootprintHelper.getLowestFootprintForDistance(optimalDistance); - // $scope.carbonData.worstCarbon = FootprintHelper.getHighestFootprintForDistance(worstDistance); + $scope.carbonData.worstCarbon = FootprintHelper.getHighestFootprintForDistance(worstDistance); } if (defaultTwoWeekUserCall) { @@ -960,15 +959,9 @@ angular.module('emission.main.metrics',['nvd3', } return distance; } - var getWorstFootprintDistance = function(metrics){ - var data = getDataFromMetrics(metrics, metric2valUser); - var distance = 0; - for(var i = 0; i < data.length; i++) { - for(var j = 0; j < data[i].values.length; j++){ - distance += data[i].values[j][1]; - } - } - return distance; + var getWorstFootprintDistance = function(modeMapSummary) { + var totalDistance = modeMapSummary.reduce((prevDistance, currModeSummary) => prevDistance + currModeSummary.values, 0); + return totalDistance; } $scope.formatCount = function(value) { diff --git a/www/templates/main-metrics.html b/www/templates/main-metrics.html index 4329eb735..911f6d611 100644 --- a/www/templates/main-metrics.html +++ b/www/templates/main-metrics.html @@ -80,9 +80,7 @@
{{'.how-it-compares'}}
{{'.optimal'}} {{carbonData.optimalCarbon}}
-->
{{'.average'}} {{carbonData.aggrCarbon | number:0 }} kg CO₂
- +
{{'.worst'}} {{carbonData.worstCarbon | number:0 }} kg CO₂
{{'.lastweek'}} {{carbonData.lastWeekUserCarbon | number:0 }} kg CO₂
-
{{'.average'}} {{carbonData.aggrCarbon | number:0 }} kg CO₂
+
{{'.average'}} kg CO₂
{{'.worst'}} {{carbonData.worstCarbon | number:0 }} kg CO₂
-
{{'.lastweek'}} {{carbonData.lastWeekUserCarbon | number:0 }} kg CO₂
+
{{'.lastweek'}} kg CO₂
-
{{'.us-2030-goal'}} {{carbonData.us2030 | number}} kg CO₂
-
{{'.us-2050-goal'}} {{carbonData.us2050 | number}} kg CO₂
- +
{{'.us-2030-goal'}} {{carbonData.us2030 | number}} kg CO₂
+
{{'.us-2050-goal'}} {{carbonData.us2050 | number}} kg CO₂
@@ -118,11 +108,11 @@

{{'.calories'}}

{{'main-metrics.equals-bananas' | translate:{bananas: numberOfBananas}:"messageformat"}}
-
{{ caloriesData.greaterLesserPct | number:0 }}% {{'metrics.greater-than-last-week' | translate }}
+
{{ caloriesData.greaterLesserPct | number:0 }}% {{'metrics.greater-than' | translate }} {{ 'metrics.last-week' | translate }}
-
{{ (-1) * caloriesData.greaterLesserPct | number:0 }}% {{'metrics.less-than-last-week' | translate }}
+
{{ (-1) * caloriesData.greaterLesserPct | number:0 }}% {{'metrics.less-than' | translate }} {{ 'metrics.last-week' | translate }}
diff --git a/www/templates/metrics/arrow-greater-lesser.html b/www/templates/metrics/arrow-greater-lesser.html new file mode 100644 index 000000000..dc3a0a402 --- /dev/null +++ b/www/templates/metrics/arrow-greater-lesser.html @@ -0,0 +1,36 @@ + + +
+ +
+
+
{{ change.low | number:0 }}% {{'metrics.greater-than' | translate }} {{ 'metrics.last-week' | translate }}
+
+
+
+
{{ change.low | number:0 }}% {{'metrics.less-than' | translate }} {{ metrics.last-week | translate }}
+
+
+
+ +
+
+
+
+
{{ (-1) * change.low | number:0 }}% {{'metrics.less-than' | translate }}
+
{{ change.low | number:0 }}% {{'metrics.greater-than' | translate }}
+
+
+
{{'metrics.or' | translate }}
+
{{'metrics.week-before' | translate }}
+
+
+
+
+
{{ (-1) * change.high | number:0 }}% {{'metrics.less-than' | translate }} {{ 'metrics.last-week' | translate }}
+
{{ change.high | number:0 }}% {{'metrics.greater-than' | translate }}
+
+
+
diff --git a/www/templates/metrics/range-display.html b/www/templates/metrics/range-display.html new file mode 100644 index 000000000..a3b3999a6 --- /dev/null +++ b/www/templates/metrics/range-display.html @@ -0,0 +1,2 @@ +{{ range.low | number:0 }} +{{ range.low | number:0 }} - {{ range.high | number:0 }} From 980bbb4aca7ce265e7887f14de5b5a88bdfd88d6 Mon Sep 17 00:00:00 2001 From: "K. Shankari" Date: Fri, 24 Dec 2021 20:07:02 -0800 Subject: [PATCH 113/175] Change the calorie calculations to also have a range Very similar to 42e8173f329bcfc86bfc991425a6c137c9cf45cf and uses some of the similar themes - if there are modes for which we don't have an MET, including "unlabeled" or any of the custom modes, we don't just ignore it. We generate a range from where the MET is 0 to the MET is the max of the available modes Uses the new custom directives defined in 42e8173f329bcfc86bfc991425a6c137c9cf45cf to display the differences and ranges properly Change the text for the food comparisons, to say "at least" and use the lower value. Changing the text to support the full range would be more complex since if the values were the same, we would have to fall back to the 1 banana/2 bananas change, but if the low and high were different, we could just use "bananas" throughout. I don't know how to do that in the translate logs, and I don't want to deal with the ng-if statements to deal with it in the HTML --- www/i18n/en.json | 6 +-- www/js/metrics-factory.js | 21 +++++++-- www/js/metrics.js | 80 ++++++++++++++++++++++----------- www/templates/main-metrics.html | 21 +++------ 4 files changed, 82 insertions(+), 46 deletions(-) diff --git a/www/i18n/en.json b/www/i18n/en.json index b225a88b9..d1cf36bf4 100644 --- a/www/i18n/en.json +++ b/www/i18n/en.json @@ -229,9 +229,9 @@ "calibrate": "Calibrate", "no-summary-data": "No summary data", "mean-speed": "Average Speed", - "equals-cookies": "Equals {cookies, plural, =0{0 homemade chocolate chip cookies} one {1 homemade chocolate chip cookie} other {# homemade chocolate chip cookies}}", - "equals-icecream": "Equals {icecream, plural, =0{0 half cups vanilla ice cream} one {1 half cup vanilla ice cream} other {# half cups vanilla ice cream}}", - "equals-bananas": "Equals {bananas, plural, =0{0 bananas} one {1 banana} other {# bananas}}" + "equals-cookies": "Equals {cookies, plural, =0{at least 0 homemade chocolate chip cookies} one {at least 1 homemade chocolate chip cookie} other {at least # homemade chocolate chip cookies}}", + "equals-icecream": "Equals {icecream, plural, =0{at least 0 half cups vanilla ice cream} one {at least 1 half cup vanilla ice cream} other {at least # half cups vanilla ice cream}}", + "equals-bananas": "Equals {bananas, plural, =0{at least 0 bananas} one {at least 1 banana} other {at least # bananas}}" }, "main-diary" : "Diary", diff --git a/www/js/metrics-factory.js b/www/js/metrics-factory.js index a3a3e9372..c762da72f 100644 --- a/www/js/metrics-factory.js +++ b/www/js/metrics-factory.js @@ -144,6 +144,7 @@ angular.module('emission.main.metrics.factory', .factory('CalorieCal', function(KVStore, METDatasetHelper, CustomDatasetHelper) { var cc = {}; + var highestMET = 0; var USER_DATA_KEY = "user-data"; cc.useCustom = false; @@ -171,15 +172,29 @@ angular.module('emission.main.metrics.factory', Number.prototype.between = function (min, max) { return this >= min && this <= max; }; - cc.getMet = function(mode, speed) { + cc.getHighestMET = function() { + if (!highestMET) { + var met = cc.getMETs(); + let metList = []; + for (var mode in met) { + var rangeList = met[mode]; + for (var range in rangeList) { + metList.push(rangeList[range].mets); + } + } + highestMET = Math.max(...metList); + } + return highestMET; + } + cc.getMet = function(mode, speed, defaultIfMissing) { if (mode == 'ON_FOOT') { console.log("CalorieCal.getMet() converted 'ON_FOOT' to 'WALKING'"); mode = 'WALKING'; } let currentMETs = cc.getMETs(); if (!currentMETs[mode]) { - console.log("CalorieCal.getMet() Illegal mode: " + mode); - return 0; //So the calorie sum does not break with wrong return type + console.warn("CalorieCal.getMet() Illegal mode: " + mode); + return defaultIfMissing; //So the calorie sum does not break with wrong return type } for (var i in currentMETs[mode]) { if (mpstomph(speed).between(currentMETs[mode][i].range[0], currentMETs[mode][i].range[1])) { diff --git a/www/js/metrics.js b/www/js/metrics.js index f56855555..ef42664d9 100644 --- a/www/js/metrics.js +++ b/www/js/metrics.js @@ -514,7 +514,6 @@ angular.module('emission.main.metrics',['nvd3', $scope.caloriesData = {}; $scope.carbonData = {}; $scope.summaryData = {}; - $scope.caloriesData.userCalories = 0; $scope.carbonData.optimalCarbon = "0 kg CO₂"; @@ -709,54 +708,83 @@ angular.module('emission.main.metrics',['nvd3', $scope.fillCalorieCardUserVals = function(userDurationSummary, userMeanSpeedSummary, twoWeeksAgoDurationSummary, twoWeeksAgoMeanSpeedSummary) { + $scope.caloriesData.userCalories = {low: 0, high: 0}; + const highestMET = CalorieCal.getHighestMET(); for (var i in userDurationSummary) { - var met = $scope.getCorrectedMetFromUserData(userDurationSummary[i], userMeanSpeedSummary[i]) - $scope.caloriesData.userCalories += - Math.round(CalorieCal.getuserCalories(userDurationSummary[i].values / 3600, met)) //+ ' cal' + var lowMET = $scope.getCorrectedMetFromUserData(userDurationSummary[i], userMeanSpeedSummary[i], 0); + var highMET = $scope.getCorrectedMetFromUserData(userDurationSummary[i], userMeanSpeedSummary[i], highestMET); + $scope.caloriesData.userCalories.low += + Math.round(CalorieCal.getuserCalories(userDurationSummary[i].values / 3600, lowMET)) //+ ' cal' + $scope.caloriesData.userCalories.high += + Math.round(CalorieCal.getuserCalories(userDurationSummary[i].values / 3600, highMET)) //+ ' cal' } - $scope.numberOfCookies = Math.floor($scope.caloriesData.userCalories/ - $scope.food.chocolateChip); - $scope.numberOfIceCreams = Math.floor($scope.caloriesData.userCalories/ - $scope.food.vanillaIceCream); - $scope.numberOfBananas = Math.floor($scope.caloriesData.userCalories/ - $scope.food.banana); + $scope.numberOfCookies = { + low: Math.floor($scope.caloriesData.userCalories.low/ + $scope.food.chocolateChip), + high: Math.floor($scope.caloriesData.userCalories.high/ + $scope.food.chocolateChip), + }; + $scope.numberOfIceCreams = { + low: Math.floor($scope.caloriesData.userCalories.low/ + $scope.food.vanillaIceCream), + high: Math.floor($scope.caloriesData.userCalories.high/ + $scope.food.vanillaIceCream), + }; + $scope.numberOfBananas = { + low: Math.floor($scope.caloriesData.userCalories.low/ + $scope.food.banana), + high: Math.floor($scope.caloriesData.userCalories.high/ + $scope.food.banana), + }; if(defaultTwoWeekUserCall) { if (twoWeeksAgoDurationSummary.length > 0) { - var twoWeeksAgoCalories = 0; + var twoWeeksAgoCalories = {low: 0, high: 0}; for (var i in twoWeeksAgoDurationSummary) { - var met = $scope.getCorrectedMetFromUserData(twoWeeksAgoDurationSummary[i], - twoWeeksAgoMeanSpeedSummary[i]) - twoWeeksAgoCalories += - Math.round(CalorieCal.getuserCalories(twoWeeksAgoDurationSummary[i].values / 3600, met)); + var lowMET = $scope.getCorrectedMetFromUserData(twoWeeksAgoDurationSummary[i], + twoWeeksAgoMeanSpeedSummary[i], 0) + var highMET = $scope.getCorrectedMetFromUserData(twoWeeksAgoDurationSummary[i], + twoWeeksAgoMeanSpeedSummary[i], highestMET) + twoWeeksAgoCalories.low += + Math.round(CalorieCal.getuserCalories(twoWeeksAgoDurationSummary[i].values / 3600, lowMET)); + twoWeeksAgoCalories.high += + Math.round(CalorieCal.getuserCalories(twoWeeksAgoDurationSummary[i].values / 3600, highMET)); } - $scope.caloriesData.lastWeekUserCalories = twoWeeksAgoCalories; + $scope.caloriesData.lastWeekUserCalories = { + low: twoWeeksAgoCalories.low, + high: twoWeeksAgoCalories.high + }; console.log("Running calorieData with ", $scope.caloriesData); // TODO: Refactor this so that we can filter out bad values ahead of time // instead of having to work around it here - $scope.caloriesData.greaterLesserPct = ($scope.caloriesData.userCalories/$scope.caloriesData.lastWeekUserCalories) * 100 - 100; + $scope.caloriesData.greaterLesserPct = { + low: ($scope.caloriesData.userCalories.low/$scope.caloriesData.lastWeekUserCalories.low) * 100 - 100, + high: ($scope.caloriesData.userCalories.high/$scope.caloriesData.lastWeekUserCalories.high) * 100 - 100, + } } } } $scope.fillCalorieAggVals = function(aggDurationSummaryAvg, aggMeanSpeedSummaryAvg) { - $scope.caloriesData.aggrCalories = 0; + $scope.caloriesData.aggrCalories = {low: 0, high: 0}; + const highestMET = CalorieCal.getHighestMET(); for (var i in aggDurationSummaryAvg) { - - var met = CalorieCal.getMet(aggDurationSummaryAvg[i].key, aggMeanSpeedSummaryAvg[i].values); - - $scope.caloriesData.aggrCalories += - Math.round(CalorieCal.getuserCalories(aggDurationSummaryAvg[i].values / 3600, met)) //+ ' cal' + var lowMET = CalorieCal.getMet(aggDurationSummaryAvg[i].key, aggMeanSpeedSummaryAvg[i].values, 0); + var highMET = CalorieCal.getMet(aggDurationSummaryAvg[i].key, aggMeanSpeedSummaryAvg[i].values, highestMET); + $scope.caloriesData.aggrCalories.low += + CalorieCal.getuserCalories(aggDurationSummaryAvg[i].values / 3600, lowMET); //+ ' cal' + $scope.caloriesData.aggrCalories.high += + CalorieCal.getuserCalories(aggDurationSummaryAvg[i].values / 3600, highMET); //+ ' cal' } } - $scope.getCorrectedMetFromUserData = function(currDurationData, currSpeedData) { + $scope.getCorrectedMetFromUserData = function(currDurationData, currSpeedData, defaultIfMissing) { if ($scope.userDataSaved()) { // this is safe because userDataSaved will never be set unless there // is stored user data that we have loaded var userDataFromStorage = $scope.savedUserData; - var met = CalorieCal.getMet(currDurationData.key, currSpeedData.values); + var met = CalorieCal.getMet(currDurationData.key, currSpeedData.values, defaultIfMissing); var gender = userDataFromStorage.gender; var heightUnit = userDataFromStorage.heightUnit; var height = userDataFromStorage.height; @@ -765,7 +793,7 @@ angular.module('emission.main.metrics',['nvd3', var age = userDataFromStorage.age; return CalorieCal.getCorrectedMet(met, gender, age, height, heightUnit, weight, weightUnit); } else { - return CalorieCal.getMet(currDurationData.key, currSpeedData.values); + return CalorieCal.getMet(currDurationData.key, currSpeedData.values, defaultIfMissing); } }; diff --git a/www/templates/main-metrics.html b/www/templates/main-metrics.html index 1e9f41a99..b7d706410 100644 --- a/www/templates/main-metrics.html +++ b/www/templates/main-metrics.html @@ -102,23 +102,16 @@

{{'.calories'}}

{{'.calibrate'}}
-
{{caloriesData.userCalories}}
-
{{'main-metrics.equals-cookies' | translate:{cookies: numberOfCookies}:"messageformat"}}
-
{{'main-metrics.equals-icecream' | translate:{icecream: numberOfIceCreams}:"messageformat"}}
-
{{'main-metrics.equals-bananas' | translate:{bananas: numberOfBananas}:"messageformat"}}
-
-
-
{{ caloriesData.greaterLesserPct | number:0 }}% {{'metrics.greater-than' | translate }} {{ 'metrics.last-week' | translate }}
-
-
-
-
{{ (-1) * caloriesData.greaterLesserPct | number:0 }}% {{'metrics.less-than' | translate }} {{ 'metrics.last-week' | translate }}
-
+
+
{{'main-metrics.equals-cookies' | translate:{cookies: numberOfCookies.low}:"messageformat"}}
+
{{'main-metrics.equals-icecream' | translate:{icecream: numberOfIceCreams.low}:"messageformat"}}
+
{{'main-metrics.equals-bananas' | translate:{bananas: numberOfBananas.low}:"messageformat"}}
+
-
{{'.average'}} {{caloriesData.aggrCalories}} cal
-
{{'.lastweek'}} {{caloriesData.lastWeekUserCalories}} cal
+
{{'.average'}} cal
+
{{'.lastweek'}} cal
From cdf4702320cb066af2ff6d69d2f3f69f662e9bda Mon Sep 17 00:00:00 2001 From: "K. Shankari" Date: Sat, 8 Jan 2022 18:07:59 -0800 Subject: [PATCH 114/175] Minor formatting fixes to the greater-lesser component - Lower case "Last week" - Distinguish between "less than" and "less" for the single value vs. range cases - ensure that the negative value is converted to positive for display even in the single value case - add quotes to display `metrics.last-week` correctly in the single value < 0 case --- www/i18n/en.json | 8 +++++--- www/templates/metrics/arrow-greater-lesser.html | 10 +++++----- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/www/i18n/en.json b/www/i18n/en.json index d1cf36bf4..45df184c2 100644 --- a/www/i18n/en.json +++ b/www/i18n/en.json @@ -110,7 +110,7 @@ "filter": "Filter", "from": "From:", "to": "To:", - "last-week": "Last week", + "last-week": "last week", "frequency": "Frequency:", "pandafreqoptions-daily": "DAILY", "pandafreqoptions-weekly": "WEEKLY", @@ -127,9 +127,11 @@ "trips-yaxis-number": "Number", "calorie-data-change": " change", "calorie-data-unknown": "Unknown...", - "greater-than": " greater ", + "greater-than": " greater than ", + "greater": " greater ", "or": "or", - "less-than": " less ", + "less-than": " less than ", + "less": " less ", "week-before": "vs. week before", "calorie-data-change-increase": " increase over a week", "calorie-data-change-decrease": " decrease over a week", diff --git a/www/templates/metrics/arrow-greater-lesser.html b/www/templates/metrics/arrow-greater-lesser.html index dc3a0a402..8f151e9f2 100644 --- a/www/templates/metrics/arrow-greater-lesser.html +++ b/www/templates/metrics/arrow-greater-lesser.html @@ -10,7 +10,7 @@
-
{{ change.low | number:0 }}% {{'metrics.less-than' | translate }} {{ metrics.last-week | translate }}
+
{{ (-1) * change.low | number:0 }}% {{'metrics.less-than' | translate }} {{ 'metrics.last-week' | translate }}
@@ -19,8 +19,8 @@
-
{{ (-1) * change.low | number:0 }}% {{'metrics.less-than' | translate }}
-
{{ change.low | number:0 }}% {{'metrics.greater-than' | translate }}
+
{{ (-1) * change.low | number:0 }}% {{'metrics.less' | translate }}
+
{{ change.low | number:0 }}% {{'metrics.greater' | translate }}
{{'metrics.or' | translate }}
@@ -29,8 +29,8 @@
-
{{ (-1) * change.high | number:0 }}% {{'metrics.less-than' | translate }} {{ 'metrics.last-week' | translate }}
-
{{ change.high | number:0 }}% {{'metrics.greater-than' | translate }}
+
{{ (-1) * change.high | number:0 }}% {{'metrics.less' | translate }}
+
{{ change.high | number:0 }}% {{'metrics.greater' | translate }}
From 00648654e21d250d854731fb2aa9f2d86b051036 Mon Sep 17 00:00:00 2001 From: "K. Shankari" Date: Sat, 15 Jan 2022 05:03:43 -0800 Subject: [PATCH 115/175] Handle the case where no trips have been labeled for two weeks This is likely fairly common for those people who have given up on labeling, so it is worth addressing. The problem is that in that case, ``` lastWeek.footprint.low = 0 thisWeek.footprint.low = 0 thisWeek.footprint.low/lastWeek.footprint.low = NaN ``` So we end up with a blank "low" on the diff display, which looks weird. To fix, we add a pre-processing step to the directive, which converts NaN -> 0 and display the % if it is >= 0 This then leads to the marginally less weird case in which we don't show the arrow and we don't show the OR To fix that as well, we remove the `ng-if` for the OR (not sure why it was ever added) and add an = for the case in which the metric is 0 --- www/js/metrics.js | 5 +++++ www/templates/metrics/arrow-greater-lesser.html | 10 ++++++---- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/www/js/metrics.js b/www/js/metrics.js index ef42664d9..cef4b61e6 100644 --- a/www/js/metrics.js +++ b/www/js/metrics.js @@ -1390,6 +1390,11 @@ angular.module('emission.main.metrics',['nvd3', scope: { change: "=" }, + link: function(scope) { + if (isNaN(scope.change.low)) scope.change.low = 0; + if (isNaN(scope.change.high)) scope.change.high = 0; + console.log("In diffdisplay, after changes, scope = ", scope); + }, templateUrl: "templates/metrics/arrow-greater-lesser.html" } }) diff --git a/www/templates/metrics/arrow-greater-lesser.html b/www/templates/metrics/arrow-greater-lesser.html index 8f151e9f2..3d75e790e 100644 --- a/www/templates/metrics/arrow-greater-lesser.html +++ b/www/templates/metrics/arrow-greater-lesser.html @@ -4,7 +4,7 @@ -->
-
+
{{ change.low | number:0 }}% {{'metrics.greater-than' | translate }} {{ 'metrics.last-week' | translate }}
@@ -19,18 +19,20 @@
+
=
{{ (-1) * change.low | number:0 }}% {{'metrics.less' | translate }}
-
{{ change.low | number:0 }}% {{'metrics.greater' | translate }}
+
{{ change.low | number:0 }}% {{'metrics.greater' | translate }}
-
{{'metrics.or' | translate }}
+
{{'metrics.or' | translate }}
{{'metrics.week-before' | translate }}
+
=
{{ (-1) * change.high | number:0 }}% {{'metrics.less' | translate }}
-
{{ change.high | number:0 }}% {{'metrics.greater' | translate }}
+
{{ change.high | number:0 }}% {{'metrics.greater' | translate }}
From 14bb822906fa8e98bba86f22ba18ddf6e535b9f5 Mon Sep 17 00:00:00 2001 From: "K. Shankari" Date: Wed, 19 Jan 2022 23:32:43 -0800 Subject: [PATCH 116/175] Handle "other" modes without mappings in the JSON The custom footprint creation currently assumes that all modes have an CO2 entry in the JSON. This is true, except in the case where the user selects "other" and puts in a custom mode. In that case, we have no mapping, so the footprint map has an entry for {mode: undefined} which causes the footprint calculations to return NaN. We instead check whether we have a mapping and return `undefined` in that case. We also filter out the undefined entries. After this change, the custom other modes will be excluded, and we will use the standard 0 - max footprint range to handle them. The calorie/MET calculation already worked like this; so this just ensures that both sets of values are consistent. This fixes https://github.com/e-mission/e-mission-docs/issues/697 --- www/js/metrics-mappings.js | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/www/js/metrics-mappings.js b/www/js/metrics-mappings.js index ec0d1b314..776d63ffa 100644 --- a/www/js/metrics-mappings.js +++ b/www/js/metrics-mappings.js @@ -363,8 +363,12 @@ angular.module('emission.main.metrics.mappings', ['emission.plugin.logger', this.range_limited_motorized = opt; console.log("Found range limited motorized mode", this.range_limited_motorized); } - return [opt.value, opt.co2PerMeter]; - }); + if (angular.isDefined(opt.co2PerMeter)) { + return [opt.value, opt.co2PerMeter]; + } else { + return undefined; + } + }).filter((modeCO2) => angular.isDefined(modeCO2));; this.customPerMeterFootprint = Object.fromEntries(modeCO2PerMeter); console.log("After populating, custom perMeterFootprint", this.customPerMeterFootprint); } From 66b97a9f1a97dd7923dabdf4a1a0fed4e90de315 Mon Sep 17 00:00:00 2001 From: "K. Shankari" Date: Thu, 20 Jan 2022 19:52:25 -0800 Subject: [PATCH 117/175] Add in the "air" mode along with the appropriate CO2 metric Note that this is actually *lower* than drove_alone because of the higher occupancy. It's close to `shared_ride` Air values are: - 2341 BTU/PMT - 159.25 lb per million BTU - (2341 * (159.25/1000000))/(1.6*2.2) = 0.09975 kg/PkmT This fixes https://github.com/e-mission/e-mission-docs/issues/696#issuecomment-1017001601 --- www/json/trip_confirm_options.json.sample | 1 + 1 file changed, 1 insertion(+) diff --git a/www/json/trip_confirm_options.json.sample b/www/json/trip_confirm_options.json.sample index e377e281a..5dbdd44d5 100644 --- a/www/json/trip_confirm_options.json.sample +++ b/www/json/trip_confirm_options.json.sample @@ -8,6 +8,7 @@ {"text":"Bus","value":"bus", "met_equivalent": "IN_VEHICLE", "co2PerMeter": 0.20727}, {"text":"Train","value":"train", "met_equivalent": "IN_VEHICLE", "co2PerMeter": 0.12256}, {"text":"Free Shuttle","value":"free_shuttle", "met_equivalent": "IN_VEHICLE", "co2PerMeter": 0.20727}, + {"text":"Air","value":"air", "met_equivalent": "IN_VEHICLE", "co2PerMeter": 0.09975}, {"text":"Other","value":"other", "met_equivalent": "UNKNOWN", "co2PerMeter": 0}], "PURPOSE" : [ {"text":"Home", "value":"home"}, From 78f241b5ffebdb8403b56245d94421fd13db06db Mon Sep 17 00:00:00 2001 From: "K. Shankari" Date: Thu, 20 Jan 2022 20:10:11 -0800 Subject: [PATCH 118/175] Add "My" to all the headings to be consistent with "My Footprint" This is a fix for the first item in https://github.com/e-mission/e-mission-docs/issues/696#issue-1108687935 --- www/i18n/en.json | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/www/i18n/en.json b/www/i18n/en.json index 45df184c2..c0907cc62 100644 --- a/www/i18n/en.json +++ b/www/i18n/en.json @@ -212,13 +212,13 @@ "main-metrics":{ "dashboard": "Dashboard", - "summary": "Summary", + "summary": "My Summary", "chart": "Chart", "change-data": "Change dates:", - "distance": "Distance", - "trips": "Trips", - "duration": "Duration", - "speed": "Speed", + "distance": "My Distance", + "trips": "My Trips", + "duration": "My Duration", + "speed": "My Speed", "footprint": "My Footprint", "how-it-compares": "Ballpark comparisons", "optimal": "Optimal (perfect mode choice for all my trips):", @@ -227,10 +227,10 @@ "lastweek": "My last week value:", "us-2030-goal": "US 2030 Goal Estimate:", "us-2050-goal": "US 2050 Goal Estimate:", - "calories": "Calories", + "calories": "My Calories", "calibrate": "Calibrate", "no-summary-data": "No summary data", - "mean-speed": "Average Speed", + "mean-speed": "My Average Speed", "equals-cookies": "Equals {cookies, plural, =0{at least 0 homemade chocolate chip cookies} one {at least 1 homemade chocolate chip cookie} other {at least # homemade chocolate chip cookies}}", "equals-icecream": "Equals {icecream, plural, =0{at least 0 half cups vanilla ice cream} one {at least 1 half cup vanilla ice cream} other {at least # half cups vanilla ice cream}}", "equals-bananas": "Equals {bananas, plural, =0{at least 0 bananas} one {at least 1 banana} other {at least # bananas}}" From de4d95fbd376264d6669c6a0d48edfc95529da7c Mon Sep 17 00:00:00 2001 From: "K. Shankari" Date: Thu, 20 Jan 2022 20:43:19 -0800 Subject: [PATCH 119/175] Switch from `worst` to `CO2 saved vs worst" This is the second item in https://github.com/e-mission/e-mission-docs/issues/696#issue-1108687935 --- www/i18n/en.json | 2 +- www/js/metrics.js | 4 ++++ www/templates/main-metrics.html | 2 +- 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/www/i18n/en.json b/www/i18n/en.json index c0907cc62..8cce9c787 100644 --- a/www/i18n/en.json +++ b/www/i18n/en.json @@ -223,7 +223,7 @@ "how-it-compares": "Ballpark comparisons", "optimal": "Optimal (perfect mode choice for all my trips):", "average": "Average for group:", - "worst": "Worst ('drive alone' for all my trips):", + "avoided": "CO₂ avoided (vs. all 'taxi'):", "lastweek": "My last week value:", "us-2030-goal": "US 2030 Goal Estimate:", "us-2050-goal": "US 2050 Goal Estimate:", diff --git a/www/js/metrics.js b/www/js/metrics.js index cef4b61e6..be2e508ee 100644 --- a/www/js/metrics.js +++ b/www/js/metrics.js @@ -826,6 +826,10 @@ angular.module('emission.main.metrics',['nvd3', }; // $scope.carbonData.optimalCarbon = FootprintHelper.getLowestFootprintForDistance(optimalDistance); $scope.carbonData.worstCarbon = FootprintHelper.getHighestFootprintForDistance(worstDistance); + $scope.carbonData.carbonAvoided = { + low: $scope.carbonData.worstCarbon - $scope.carbonData.userCarbon.low, + high: $scope.carbonData.worstCarbon - $scope.carbonData.userCarbon.high, + }; } if (defaultTwoWeekUserCall) { diff --git a/www/templates/main-metrics.html b/www/templates/main-metrics.html index b7d706410..2cc925f56 100644 --- a/www/templates/main-metrics.html +++ b/www/templates/main-metrics.html @@ -73,7 +73,7 @@
{{'.how-it-compares'}}
{{'.optimal'}} {{carbonData.optimalCarbon}}
-->
{{'.average'}} kg CO₂
-
{{'.worst'}} {{carbonData.worstCarbon | number:0 }} kg CO₂
+
{{'.avoided'}} kg CO₂
{{'.lastweek'}} kg CO₂
@@ -98,12 +101,12 @@
{{'.how-it-compares'}}
-

{{'.calories'}}

+

{{'.calories'}}

{{'.calibrate'}}
-
+
kcal
{{'main-metrics.equals-cookies' | translate:{cookies: numberOfCookies.low}:"messageformat"}}
{{'main-metrics.equals-icecream' | translate:{icecream: numberOfIceCreams.low}:"messageformat"}}
{{'main-metrics.equals-bananas' | translate:{bananas: numberOfBananas.low}:"messageformat"}}
From 4f390af9718b62c0af1f8db767850223599ce4e2 Mon Sep 17 00:00:00 2001 From: "K. Shankari" Date: Fri, 25 Feb 2022 10:56:50 -0800 Subject: [PATCH 136/175] Don't display the differences if it is not a two week call Since the last week value is not computed anyway. https://github.com/e-mission/e-mission-docs/issues/705#issuecomment-1051106812 --- www/js/metrics.js | 20 ++++++++++---------- www/templates/main-metrics.html | 4 ++-- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/www/js/metrics.js b/www/js/metrics.js index d52616547..4bfe6ef98 100644 --- a/www/js/metrics.js +++ b/www/js/metrics.js @@ -17,7 +17,7 @@ angular.module('emission.main.metrics',['nvd3', $rootScope, $location, $state, ReferHelper, Logger, $translate) { var lastTwoWeeksQuery = true; - var defaultTwoWeekUserCall = true; + $scope.defaultTwoWeekUserCall = true; var DURATION = "duration"; var MEAN_SPEED = "mean_speed"; @@ -501,7 +501,7 @@ angular.module('emission.main.metrics',['nvd3', $ionicLoading.show({ template: $translate.instant('loading') }); - if(!defaultTwoWeekUserCall){ + if(!$scope.defaultTwoWeekUserCall){ $scope.uictrl.currentString = $translate.instant('metrics.custom'); $scope.uictrl.current = false; } @@ -535,14 +535,14 @@ angular.module('emission.main.metrics',['nvd3', $ionicLoading.hide(); console.log("user results ", results); if(results.user_metrics.length == 1){ - console.log("defaultTwoWeekUserCall = "+defaultTwoWeekUserCall); - defaultTwoWeekUserCall = false; + console.log("$scope.defaultTwoWeekUserCall = "+$scope.defaultTwoWeekUserCall); + $scope.defaultTwoWeekUserCall = false; // If there is no data from last week (ex. new user) // Don't store the any other data as last we data } $scope.fillUserValues(results.user_metrics); $scope.summaryData.defaultSummary = $scope.summaryData.userSummary; - defaultTwoWeekUserCall = false; //If there is data from last week store the data only first time + $scope.defaultTwoWeekUserCall = false; //If there is data from last week store the data only first time $scope.uictrl.showContent = true; if (angular.isDefined($scope.chartDataUser)) { $scope.$apply(function() { @@ -595,7 +595,7 @@ angular.module('emission.main.metrics',['nvd3', METRIC_LIST.forEach((m) => $scope.userTwoWeeksAgo[m] = []); - if(defaultTwoWeekUserCall){ + if($scope.defaultTwoWeekUserCall){ for(var i in user_metrics_arr[0]) { if(seventhDayAgo.isSameOrBefore(moment.unix(user_metrics_arr[0][i].ts).utc())){ METRIC_LIST.forEach((m, idx) => $scope.userCurrentResults[m].push(user_metrics_arr[idx][i])); @@ -645,7 +645,7 @@ angular.module('emission.main.metrics',['nvd3', $scope.fillAggregateValues = function(agg_metrics_arr) { METRIC_LIST.forEach((m) => $scope.aggCurrentResults[m] = []); - if (defaultTwoWeekUserCall) { + if ($scope.defaultTwoWeekUserCall) { METRIC_LIST.forEach((m, idx) => $scope.aggCurrentResults[m] = agg_metrics_arr[idx].slice(0,7)); } else { METRIC_LIST.forEach((m, idx) => $scope.aggCurrentResults[m] = agg_metrics_arr[idx]); @@ -743,7 +743,7 @@ angular.module('emission.main.metrics',['nvd3', $scope.food.banana), }; - if(defaultTwoWeekUserCall) { + if($scope.defaultTwoWeekUserCall) { if (twoWeeksAgoDurationSummary.length > 0) { var twoWeeksAgoCalories = {low: 0, high: 0}; for (var i in twoWeeksAgoDurationSummary) { @@ -844,7 +844,7 @@ angular.module('emission.main.metrics',['nvd3', $scope.carbon.phoneCharge), }; - if (defaultTwoWeekUserCall) { + if ($scope.defaultTwoWeekUserCall) { // This is a default call in which we retrieved the current week and // the previous week of data if (twoWeeksAgoDistance.length > 0) { @@ -1199,7 +1199,7 @@ angular.module('emission.main.metrics',['nvd3', initSelect(); $scope.doRefresh = function() { - defaultTwoWeekUserCall = true; + $scope.defaultTwoWeekUserCall = true; getMetrics(); } diff --git a/www/templates/main-metrics.html b/www/templates/main-metrics.html index d50c48589..391e8af8c 100644 --- a/www/templates/main-metrics.html +++ b/www/templates/main-metrics.html @@ -68,7 +68,7 @@

{{'.footprint'}}

- +
@@ -110,7 +110,7 @@

{{'.calories'}}

{{'main-metrics.equals-cookies' | translate:{cookies: numberOfCookies.low}:"messageformat"}}
{{'main-metrics.equals-icecream' | translate:{icecream: numberOfIceCreams.low}:"messageformat"}}
{{'main-metrics.equals-bananas' | translate:{bananas: numberOfBananas.low}:"messageformat"}}
- +
From 99a8c1c21d99b65387bd99b6b04753bbb921afd8 Mon Sep 17 00:00:00 2001 From: "K. Shankari" Date: Fri, 25 Feb 2022 11:36:27 -0800 Subject: [PATCH 137/175] Ensure that the twoWeeksAgo flag is set consistently - Set it only when we are actually make a two week long call - Don't set it on every refresh since we don't actually retrieve two weeks worth of information This implements https://github.com/e-mission/e-mission-docs/issues/705#issuecomment-1051118140 --- www/js/metrics.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/www/js/metrics.js b/www/js/metrics.js index 4bfe6ef98..e9a03e0b5 100644 --- a/www/js/metrics.js +++ b/www/js/metrics.js @@ -453,9 +453,11 @@ angular.module('emission.main.metrics',['nvd3', var tempFrom = moment2Timestamp(moment().utc().startOf('day').subtract(14, 'days')); var tempTo = moment2Timestamp(moment().utc().startOf('day').subtract(1, 'days')) lastTwoWeeksQuery = false; // Only get last week's data once + $scope.defaultTwoWeekUserCall = true; } else { var tempFrom = moment2Timestamp($scope.selectCtrl.fromDateTimestamp); var tempTo = moment2Timestamp($scope.selectCtrl.toDateTimestamp); + $scope.defaultTwoWeekUserCall = false; } data = { freq: $scope.selectCtrl.pandaFreq, @@ -1199,7 +1201,6 @@ angular.module('emission.main.metrics',['nvd3', initSelect(); $scope.doRefresh = function() { - $scope.defaultTwoWeekUserCall = true; getMetrics(); } From d9c340e9ad045886db64f2476edb8ba9a5190cdd Mon Sep 17 00:00:00 2001 From: "K. Shankari" Date: Fri, 25 Feb 2022 17:37:12 -0800 Subject: [PATCH 138/175] Humanize the dashboard values better Add a little bit of a humanization for the values - only show the range if the difference is significant - format the values with decimal points if it is small (e.g. < 1), without decimal points if it is large (at least integer size) --- www/js/metrics.js | 16 ++++++++++++++++ www/templates/metrics/range-display.html | 4 ++-- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/www/js/metrics.js b/www/js/metrics.js index e9a03e0b5..19d10f254 100644 --- a/www/js/metrics.js +++ b/www/js/metrics.js @@ -1420,6 +1420,22 @@ angular.module('emission.main.metrics',['nvd3', scope: { range: "=" }, + link: function(scope) { + // console.log("RANGE DISPLAY "+JSON.stringify(scope.range)); + var humanize = function(num) { + if (Math.abs(num) < 1) { + return num.toFixed(2); + } else { + return num.toFixed(0); + } + } + + if (Math.abs(scope.range.high - scope.range.low) < 1) { + scope.tinyDiff = true; + } + scope.lowFmt = humanize(scope.range.low); + scope.highFmt = humanize(scope.range.high); + }, templateUrl: "templates/metrics/range-display.html" } }); diff --git a/www/templates/metrics/range-display.html b/www/templates/metrics/range-display.html index a3b3999a6..fa8c3581e 100644 --- a/www/templates/metrics/range-display.html +++ b/www/templates/metrics/range-display.html @@ -1,2 +1,2 @@ -{{ range.low | number:0 }} -{{ range.low | number:0 }} - {{ range.high | number:0 }} +{{ lowFmt }} +{{ lowFmt }} - {{ highFmt }} From 0dd0ebda7065fe2c15fba67141222cb73d545a99 Mon Sep 17 00:00:00 2001 From: "K. Shankari" Date: Fri, 25 Feb 2022 17:49:36 -0800 Subject: [PATCH 139/175] Only display the worst carbon and the aggregate carbon once they exist As part of the humanize change d9c340e9ad045886db64f2476edb8ba9a5190cdd we reformat the values in the scope. This means that when the input values are changed, we can't detect that the `range-display` values have also been recomputed. So for elements that are created before the values are retrieved from the server, the range low and high are blank. We could `$watch` or something for the values to change and then call `$apply` again, but an easier option is to just defer the initialization of the metrics until the value is actually set. --- www/templates/main-metrics.html | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/www/templates/main-metrics.html b/www/templates/main-metrics.html index 391e8af8c..c8c54b916 100644 --- a/www/templates/main-metrics.html +++ b/www/templates/main-metrics.html @@ -77,7 +77,7 @@
{{'.how-it-compares'}}
{{'.optimal'}} {{carbonData.optimalCarbon}}
-->
{{'.average'}} kg CO₂
-
{{'.avoided'}} kg CO₂
+
{{'.avoided'}} kg CO₂
{{'.lastweek'}} kg CO₂
- +
@@ -110,7 +110,7 @@

{{'.calories'}}

{{'main-metrics.equals-cookies' | translate:{cookies: numberOfCookies.low}:"messageformat"}}
{{'main-metrics.equals-icecream' | translate:{icecream: numberOfIceCreams.low}:"messageformat"}}
{{'main-metrics.equals-bananas' | translate:{bananas: numberOfBananas.low}:"messageformat"}}
- +

From 6f59cc62c568463c16a6c78412e430c8a2daf57b Mon Sep 17 00:00:00 2001 From: "K. Shankari" Date: Wed, 23 Mar 2022 09:20:44 -0700 Subject: [PATCH 142/175] Fix the instructions for turning off the "force https" requirement on debug builds The previous instructions generated a conflict in AndroidManifest, missing permissions and a crashing app --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a6813a6b5..536a24407 100644 --- a/README.md +++ b/README.md @@ -139,7 +139,7 @@ $ source setup/activate_native.sh If connecting to a development server over http, make sure to turn on http support on android ``` - + ``` From 351edfc73ff2718e87f4a258accc723e80e2e6ae Mon Sep 17 00:00:00 2001 From: "K. Shankari" Date: Wed, 23 Mar 2022 09:24:20 -0700 Subject: [PATCH 143/175] Bump up the version numbers to support the fix for the unused app restrictions issue: https://github.com/e-mission/e-mission-docs/issues/710 Initial fix: https://github.com/e-mission/e-mission-data-collection/pull/197 Release: https://github.com/e-mission/e-mission-data-collection/releases/tag/v1.7.1 --- config.cordovabuild.xml | 2 +- package.cordovabuild.json | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/config.cordovabuild.xml b/config.cordovabuild.xml index dc0165871..efb5b760d 100644 --- a/config.cordovabuild.xml +++ b/config.cordovabuild.xml @@ -1,5 +1,5 @@ - + emission A commute pattern tracker and carbon footprint estimator. diff --git a/package.cordovabuild.json b/package.cordovabuild.json index d89250549..652fa1411 100644 --- a/package.cordovabuild.json +++ b/package.cordovabuild.json @@ -1,6 +1,6 @@ { "name": "edu.berkeley.eecs.emission", - "version": "3.2.0", + "version": "3.2.1", "displayName": "emission", "license": "BSD-3-Clause", "repository": { @@ -78,7 +78,7 @@ "cordova-plugin-app-version": "0.1.12", "cordova-plugin-customurlscheme": "5.0.2", "cordova-plugin-device": "2.0.3", - "cordova-plugin-em-datacollection": "git+https://github.com/e-mission/e-mission-data-collection.git#v1.7.0", + "cordova-plugin-em-datacollection": "git+https://github.com/e-mission/e-mission-data-collection.git#v1.7.1", "cordova-plugin-em-jwt-auth": "git+https://github.com/e-mission/cordova-jwt-auth.git#v1.6.5", "cordova-plugin-em-server-communication": "git+https://github.com/e-mission/cordova-server-communication.git#v1.2.3", "cordova-plugin-em-serversync": "git+https://github.com/e-mission/cordova-server-sync.git#v1.2.7", From 82a2e531dc11ba11dbb86093b82f1374d40b164e Mon Sep 17 00:00:00 2001 From: "K. Shankari" Date: Wed, 23 Mar 2022 10:19:13 -0700 Subject: [PATCH 144/175] Remove most of the devDependencies from leaflet Since we don't build it now and we are never going to build it --- www/manual_lib/leaflet/package.json | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/www/manual_lib/leaflet/package.json b/www/manual_lib/leaflet/package.json index 5070cd8ea..e996f2965 100644 --- a/www/manual_lib/leaflet/package.json +++ b/www/manual_lib/leaflet/package.json @@ -2,20 +2,6 @@ "name": "leaflet", "version": "0.7.7", "description": "JavaScript library for mobile-friendly interactive maps", - "devDependencies": { - "copyfiles": "^0.2.1", - "happen": "~0.2.0", - "jake": "~8.0.12", - "jshint": "~2.8.0", - "karma": "~0.13.14", - "karma-chrome-launcher": "^0.2.1", - "karma-coverage": "~0.5.3", - "karma-mocha": "~0.2.0", - "karma-phantomjs-launcher": "^0.2.1", - "mocha": "~2.3.3", - "tin": "^0.5.0", - "uglify-js": "~3.6.6" - }, "main": "dist/leaflet-src.js", "scripts": { "test": "jake test", From bf96df31a0aceb809f68f402f92b6b59160b9da4 Mon Sep 17 00:00:00 2001 From: "K. Shankari" Date: Mon, 28 Mar 2022 12:43:51 -0700 Subject: [PATCH 145/175] Fix "second level of end checks" for the user label matching As part of https://github.com/e-mission/e-mission-phone/commit/3ec573446b2e56f865750d3da03744c2aafed158 we changed the input from a trip geojson to a trip object. But we forgot to change one of the code paths, which caused a regression. Fixed by changing the variable and the format of the variable. Testing done: - loaded fake manual entries for a test user - before the change, got the error - after the change, did not get the error This fixes https://github.com/e-mission/e-mission-docs/issues/713 --- www/js/diary/services.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/www/js/diary/services.js b/www/js/diary/services.js index 006649ddd..b86330491 100644 --- a/www/js/diary/services.js +++ b/www/js/diary/services.js @@ -439,9 +439,9 @@ angular.module('emission.main.diary.services', ['emission.plugin.logger', var endChecks = (userInput.data.end_ts <= trip.end_ts || (userInput.data.end_ts - trip.end_ts) <= 15 * 60); if (startChecks && !endChecks) { - if (angular.isDefined(nextTripgj)) { - endChecks = userInput.data.end_ts <= nextTripgj.data.properties.start_ts; - Logger.log("Second level of end checks when the next trip is defined("+userInput.data.end_ts+" <= "+ nextTripgj.data.properties.start_ts+") = "+endChecks); + if (angular.isDefined(nextTrip)) { + endChecks = userInput.data.end_ts <= nextTrip.start_ts; + Logger.log("Second level of end checks when the next trip is defined("+userInput.data.end_ts+" <= "+ nextTrip.start_ts+") = "+endChecks); } else { // next trip is not defined, last trip endChecks = (userInput.data.end_local_dt.day == userInput.data.start_local_dt.day) From 5065c80ee7205b495df122e89cb382768688adc5 Mon Sep 17 00:00:00 2001 From: "K. Shankari" Date: Wed, 30 Mar 2022 08:47:51 -0700 Subject: [PATCH 146/175] Update the documentation to remove dependency on android studio This is an initial fix for https://github.com/e-mission/e-mission-docs/issues/711 Additional fix is to automate some of the steps by including them in the setup and activate scripts. --- README.md | 10 ++++++++-- setup/android_sdk_packages | 22 ++++++++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) create mode 100644 setup/android_sdk_packages diff --git a/README.md b/README.md index 536a24407..b10448590 100644 --- a/README.md +++ b/README.md @@ -94,8 +94,14 @@ Pre-requisites - or this [supposedly easier to use repo](https://github.com/xcpretty/xcode-install) - **NOTE**: the basic xcode install on Catalina was messed up for me due to a prior installation of command line tools. [These workarounds helped](https://github.com/nodejs/node-gyp/blob/master/macOS_Catalina.md). - git -- the most recent version of android studio - - **NOTE**: although Catalina has a `/usr/bin/java`, trying to run it gives the error `No Java runtime present, requesting install.`. The build now requires Java 11. Installed [OpenJDK 11 (Temurin) using AdoptOpenJDK](https://adoptopenjdk.net/releases.html) to be consistent with the CI. +- Java 11. Tested with [OpenJDK 11 (Temurin) using AdoptOpenJDK](https://adoptopenjdk.net/releases.html). +- android command line tools version 8092744, [downloaded from the android site](https://developer.android.com/studio/) and installed (on OSX) in `~/Library/Android/sdk/cmdline-tools` +- android SDK, installed using `~/Library/Android/cmdline-tools/bin/sdkmanager --package_file=setup/android_sdk_packages` +- SDK root and PATH environment variables set correctly + ``` + export ANDROID_SDK_ROOT=~/Library/Android/sdk` + export PATH=$ANDROID_SDK_ROOT/sdk/cmdline-tools/bin:$ANDROID_SDK_ROOT/emulator:$PATH + ``` Important --- diff --git a/setup/android_sdk_packages b/setup/android_sdk_packages new file mode 100644 index 000000000..38d07d1b8 --- /dev/null +++ b/setup/android_sdk_packages @@ -0,0 +1,22 @@ +build-tools;30.0.1 +build-tools;30.0.2 +build-tools;30.0.3 +build-tools;31.0.0 +emulator +extras;google;google_play_services +extras;intel;Hardware_Accelerated_Execution_Manager +patcher;v4 +platform-tools +platforms;android-30 +platforms;android-31 +system-images;android-22;google_apis;x86_64 +system-images;android-23;google_apis;x86_64 +system-images;android-24;google_apis_playstore;x86 +system-images;android-25;google_apis_playstore;x86 +system-images;android-26;google_apis_playstore;x86 +system-images;android-27;google_apis_playstore;x86 +system-images;android-28;google_apis_playstore;x86_64 +system-images;android-29;google_apis_playstore;x86 +system-images;android-29;google_apis_playstore;x86_64 +system-images;android-30;google_apis_playstore;x86 +system-images;android-30;google_apis_playstore;x86_64 From 4f1682715d3675576465e949aa75e71912089c75 Mon Sep 17 00:00:00 2001 From: "K. Shankari" Date: Wed, 30 Mar 2022 11:28:17 -0700 Subject: [PATCH 147/175] Add some additional log statements - See if gradle is installed (prepartory to removing the manual install) - ensure that we use java 11 everywhere --- .github/workflows/android-build.yml | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/.github/workflows/android-build.yml b/.github/workflows/android-build.yml index 62d075a2c..38da371a9 100644 --- a/.github/workflows/android-build.yml +++ b/.github/workflows/android-build.yml @@ -26,20 +26,26 @@ jobs: - uses: actions/checkout@v2 # Runs a single command using the runners shell - - name: Print the java version + - name: Print the java and gradle versions run: | + echo "Default java version" java -version + echo "Setting to Java 11 instead" export JAVA_HOME=$JAVA_HOME_11_X64 java -version + echo "Checking gradle" + which gradle + gradle -version - name: Tries to figure out where android is installed run: | - echo "Android listed at $ANDROID_HOME" + echo "Android listed at $ANDROID_SDK_ROOT" ls -al /opt/ - name: Setup the cordova environment shell: bash -l {0} run: | + export JAVA_HOME=$JAVA_HOME_11_X64 bash setup/setup_android_native.sh - name: Check tool versions From 70fdf38dccb7829d990da981366be970c5c87049 Mon Sep 17 00:00:00 2001 From: "K. Shankari" Date: Wed, 30 Mar 2022 11:32:58 -0700 Subject: [PATCH 148/175] Automate the installation of the prerequistes This is in a separate scripts because: - it takes a long time - it only needs to be run once per computer Change readme to remove prior manual instructions and indicate that it is enough to run the prerequisite script Change activate to set the PATH variables correctly --- README.md | 28 ++++++++++++++++++---- setup/activate_native.sh | 3 +++ setup/prereq_android_sdk_install.sh | 37 +++++++++++++++++++++++++++++ 3 files changed, 63 insertions(+), 5 deletions(-) create mode 100644 setup/prereq_android_sdk_install.sh diff --git a/README.md b/README.md index b10448590..c9b029ec0 100644 --- a/README.md +++ b/README.md @@ -95,14 +95,32 @@ Pre-requisites - **NOTE**: the basic xcode install on Catalina was messed up for me due to a prior installation of command line tools. [These workarounds helped](https://github.com/nodejs/node-gyp/blob/master/macOS_Catalina.md). - git - Java 11. Tested with [OpenJDK 11 (Temurin) using AdoptOpenJDK](https://adoptopenjdk.net/releases.html). -- android command line tools version 8092744, [downloaded from the android site](https://developer.android.com/studio/) and installed (on OSX) in `~/Library/Android/sdk/cmdline-tools` -- android SDK, installed using `~/Library/Android/cmdline-tools/bin/sdkmanager --package_file=setup/android_sdk_packages` -- SDK root and PATH environment variables set correctly +- android SDK; install manually or use setup script below. Note that you only need to run this once **per computer**. ``` - export ANDROID_SDK_ROOT=~/Library/Android/sdk` - export PATH=$ANDROID_SDK_ROOT/sdk/cmdline-tools/bin:$ANDROID_SDK_ROOT/emulator:$PATH + $ bash setup/prereq_android_sdk_install.sh ``` +
Expected output + + ``` + Downloading the command line tools for mac + % Total % Received % Xferd Average Speed Time Time Time Current + Dload Upload Total Spent Left Speed + 100 114M 100 114M 0 0 8092k 0 0:00:14 0:00:14 --:--:-- 8491k + Found downloaded file at /tmp/commandlinetools-mac-8092744_latest.zip + Installing the command line tools + Archive: /tmp/commandlinetools-mac-8092744_latest.zip + ... + Downloading the android SDK. This will take a LONG time and will require you to agree to lots of licenses. + Do you wish to continue? (Y/N)Y + ... + Accept? (y/N): Y + ... + [====== ] 17% Downloading x86_64-23_r33.zip... s + ``` + +
+ Important --- Most of the recent issues encountered have been due to incompatible setup. We diff --git a/setup/activate_native.sh b/setup/activate_native.sh index 91e7a9321..27a2cd99d 100644 --- a/setup/activate_native.sh +++ b/setup/activate_native.sh @@ -13,5 +13,8 @@ fi echo "Activating sdkman, and by default, gradle" source ~/.sdkman/bin/sdkman-init.sh +echo "Ensuring that we use the most recent version of the command line tools" +export PATH=$ANDROID_SDK_ROOT/sdk/cmdline-tools/bin:$ANDROID_SDK_ROOT/emulator:$PATH + echo "Configuring the repo for building native code" ./bin/configure_xml_and_json.js cordovabuild diff --git a/setup/prereq_android_sdk_install.sh b/setup/prereq_android_sdk_install.sh new file mode 100644 index 000000000..290338f29 --- /dev/null +++ b/setup/prereq_android_sdk_install.sh @@ -0,0 +1,37 @@ +TOOLS_VERSION=8092744 +TOOLS_ZIP_FILENAME=commandlinetools-mac-${TOOLS_VERSION}_latest.zip + +if [ -z $ANDROID_SDK_ROOT ]; +then + echo "ANDROID_SDK_ROOT not set, install location unknown not found, exiting" + exit 1 +else + echo "ANDROID_SDK_ROOT=$ANDROID_SDK_ROOT" +fi + +echo "Downloading the command line tools for mac" +curl -o /tmp/$TOOLS_ZIP_FILENAME https://dl.google.com/android/repository/$TOOLS_ZIP_FILENAME + +if [ -f /tmp/$TOOLS_ZIP_FILENAME ]; +then + echo "Found downloaded file at /tmp/$TOOLS_ZIP_FILENAME" +else + echo "Download failed, please retry, or download from https://developer.android.com/studio/ and save to /tmp" + exit 1 +fi + +echo "Installing the command line tools" +mkdir -p $ANDROID_SDK_ROOT/cmdline-tools/latest +unzip /tmp/$TOOLS_ZIP_FILENAME -d $ANDROID_SDK_ROOT/cmdline-tools/latest/ +mv $ANDROID_SDK_ROOT/cmdline-tools/latest/cmdline-tools/* $ANDROID_SDK_ROOT/cmdline-tools/latest/ +rm -rf $ANDROID_SDK_ROOT/cmdline-tools/latest/cmdline-tools/ + +echo "Downloading the android SDK. This will take a LONG time and will require you to agree to lots of licenses." +read -p "Do you wish to continue? (Y/N)" CONTINUE +if [ $CONTINUE == "Y" ]; +then + $ANDROID_SDK_ROOT/cmdline-tools/latest/bin/sdkmanager --package_file=setup/android_sdk_packages +else + echo "Please install this before proceeding with the installation steps" + exit 1 +fi From 00cac158d29ee8eec7e0fb50316b777f1804b323 Mon Sep 17 00:00:00 2001 From: "K. Shankari" Date: Wed, 30 Mar 2022 11:45:33 -0700 Subject: [PATCH 149/175] Check the automated SDK install process Every time it changes, and every week to catch regressions --- .../android-automated-sdk-install.sh | 74 +++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 .github/workflows/android-automated-sdk-install.sh diff --git a/.github/workflows/android-automated-sdk-install.sh b/.github/workflows/android-automated-sdk-install.sh new file mode 100644 index 000000000..0c3391822 --- /dev/null +++ b/.github/workflows/android-automated-sdk-install.sh @@ -0,0 +1,74 @@ +name: osx-install-android-sdk-automated + +# Controls when the action will run. Triggers the workflow on push or pull request +# events but only for the master branch +on: + push: + paths: + - 'setup/prereq_android_sdk_install.sh' + pull_request: + paths: + - 'setup/prereq_android_sdk_install.sh' + schedule: + # * is a special character in YAML so you have to quote this string + - cron: '5 4 * * 0' + +# A workflow run is made up of one or more jobs that can run sequentially or in parallel +jobs: + # This workflow contains a single job called "build" + install: + # The type of runner that the job will run on + runs-on: macos-latest + + env: + NEW_ANDROID_SDK_ROOT: /tmp/new-install/Android/sdk + + # Steps represent a sequence of tasks that will be executed as part of the job + steps: + # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it + - uses: actions/checkout@v2 + + # Runs a single command using the runners shell + - name: Print the current SDK root and version + run: | + echo "SDK root before install $ANDROID_SDK_ROOT" + cat $ANDROID_SDK_ROOT/cmdline-tools/latest/source.properties + echo "Existing installed packages" + $ANDROID_SDK_ROOT/cmdline-tools/latest/bin/sdkmanager --list-installed + + - name: Install to a new SDK root + run: | + export ANDROID_SDK_ROOT=$NEW_ANDROID_SDK_ROOT + echo "New SDK root $ANDROID_SDK_ROOT" + yes Y | setup/prereq_android_sdk_install.sh + + - name: Verify that all packages are as expected + shell: bash -l {0} + run: | + echo "Comparing $ANDROID_SDK_ROOT and $NEW_ANDROID_SDK_ROOT" + $ANDROID_SDK_ROOT/cmdline-tools/latest/bin/sdkmanager --list_installed > /tmp/existing_packages + $NEW_ANDROID_SDK_ROOT/cmdline-tools/latest/bin/sdkmanager --list_installed > /tmp/new_packages + diff /tmp/existing_packages /tmp/new_packages + + - name: Verify that directory structure is consistent + shell: bash -l {0} + run: | + export ANDROID_SDK_ROOT=$NEW_ANDROID_SDK_ROOT + echo "New SDK root $ANDROID_SDK_ROOT" + ls -al $ANDROID_SDK_ROOT + if [ ! -f $ANDROID_SDK_ROOT/emulator ]; then exit 1 fi + if [ ! -f $ANDROID_SDK_ROOT/build-tools ]; then exit 1 fi + if [ ! -f $ANDROID_SDK_ROOT/patcher ]; then exit 1 fi + if [ ! -f $ANDROID_SDK_ROOT/extras ]; then exit 1 fi + if [ ! -f $ANDROID_SDK_ROOT/platforms ]; then exit 1 fi + if [ ! -f $ANDROID_SDK_ROOT/platform-tools ]; then exit 1 fi + if [ ! -f $ANDROID_SDK_ROOT/system-images ]; then exit 1 fi + + - name: Ensure that the path is correct and installed programs are runnable + shell: bash -l {0} + run: | + export JAVA_HOME=$JAVA_HOME_11_X64 + export ANDROID_SDK_ROOT=$NEW_ANDROID_SDK_ROOT + echo "New SDK root $ANDROID_SDK_ROOT" + source setup/activate_native.sh + $ANDROID_SDK_ROOT/emulator/emulator -list-avds From 58ed7660ca72515317bb0b952405922da8024778 Mon Sep 17 00:00:00 2001 From: "K. Shankari" Date: Wed, 30 Mar 2022 13:05:29 -0700 Subject: [PATCH 150/175] Change the SDK install to trigger the workflow --- setup/prereq_android_sdk_install.sh | 2 ++ 1 file changed, 2 insertions(+) diff --git a/setup/prereq_android_sdk_install.sh b/setup/prereq_android_sdk_install.sh index 290338f29..5ed48f8c8 100644 --- a/setup/prereq_android_sdk_install.sh +++ b/setup/prereq_android_sdk_install.sh @@ -1,6 +1,8 @@ TOOLS_VERSION=8092744 TOOLS_ZIP_FILENAME=commandlinetools-mac-${TOOLS_VERSION}_latest.zip +echo "Installing command line tools from $TOOLS_ZIP_FILENAME" + if [ -z $ANDROID_SDK_ROOT ]; then echo "ANDROID_SDK_ROOT not set, install location unknown not found, exiting" From 24230302f6eee83c3489172b1692cb09e70911a9 Mon Sep 17 00:00:00 2001 From: shankari Date: Mon, 4 Apr 2022 15:10:47 -0700 Subject: [PATCH 151/175] Get the installation checks to actually work (#817) * Comment out everything else and just echo the initial environment variables * Run the test CI for all pushes and PRs So that at least it shows up * Change the automated install to be identical to the CI workflow * Fix the file ending * Now introduce the actual changes we want to test * Fix the list_installed syntax * Enable all the other steps as well * actually run the install script Not sure why it is hanging through * Add some logging statements to check when the install is complete + ensure that this only runs when the prerequisite script is changed * Ensure that we explicitly exit from the script Since we are running it with `yes Y | ...` and it does not appear to exit automatically * Simplify the install script so we can see why it doesn't exit properly * Remove all prompts and make sure that it works * Remove the pipe to confirm that this the problem * Restore the prompts We will try different options to pass in the prompt since the `yes` pipe doesn't seem to work https://www.baeldung.com/linux/bash-interactive-prompts * Reintroduce the actual install now that the printf workaround seems to work * Fix install check and diff check - Diff check is expected to fail - Install check should be the last item so that the workflow will fail correctly * Add -x so we print lines before executing them Which makes it easier to find errors in these giant scripts * Fix syntax of single line command by adding appropriate semicolons ``` $ if [ ! -f $ANDROID_SDK_ROOT/emulator ]; then echo "not found" fi > -bash: syntax error: unexpected end of file $ if [ ! -f $ANDROID_SDK_ROOT/emulator ]; then echo "not found"; fi not found ``` * Fix the checks to look for directories and not files * Split the checks into two so we detect if either check fails * Restore the default CI to only run on the master branch Reverts "Run the test CI for all pushes and PRs" which will not be a separate commit once we squash and merge --- ...l.sh => android-automated-sdk-install.yml} | 32 ++++++++++++------- setup/prereq_android_sdk_install.sh | 2 ++ 2 files changed, 22 insertions(+), 12 deletions(-) rename .github/workflows/{android-automated-sdk-install.sh => android-automated-sdk-install.yml} (71%) diff --git a/.github/workflows/android-automated-sdk-install.sh b/.github/workflows/android-automated-sdk-install.yml similarity index 71% rename from .github/workflows/android-automated-sdk-install.sh rename to .github/workflows/android-automated-sdk-install.yml index 0c3391822..d32d08d67 100644 --- a/.github/workflows/android-automated-sdk-install.sh +++ b/.github/workflows/android-automated-sdk-install.yml @@ -34,13 +34,13 @@ jobs: echo "SDK root before install $ANDROID_SDK_ROOT" cat $ANDROID_SDK_ROOT/cmdline-tools/latest/source.properties echo "Existing installed packages" - $ANDROID_SDK_ROOT/cmdline-tools/latest/bin/sdkmanager --list-installed + $ANDROID_SDK_ROOT/cmdline-tools/latest/bin/sdkmanager --list_installed - name: Install to a new SDK root run: | export ANDROID_SDK_ROOT=$NEW_ANDROID_SDK_ROOT echo "New SDK root $ANDROID_SDK_ROOT" - yes Y | setup/prereq_android_sdk_install.sh + printf "Y\nY\nY\nY\nY\n" | bash setup/prereq_android_sdk_install.sh - name: Verify that all packages are as expected shell: bash -l {0} @@ -48,21 +48,22 @@ jobs: echo "Comparing $ANDROID_SDK_ROOT and $NEW_ANDROID_SDK_ROOT" $ANDROID_SDK_ROOT/cmdline-tools/latest/bin/sdkmanager --list_installed > /tmp/existing_packages $NEW_ANDROID_SDK_ROOT/cmdline-tools/latest/bin/sdkmanager --list_installed > /tmp/new_packages - diff /tmp/existing_packages /tmp/new_packages + diff -uw /tmp/existing_packages /tmp/new_packages + echo "Expected differences; emulators, SDK versions, tool versions" - name: Verify that directory structure is consistent - shell: bash -l {0} + shell: bash -l -x {0} run: | export ANDROID_SDK_ROOT=$NEW_ANDROID_SDK_ROOT echo "New SDK root $ANDROID_SDK_ROOT" ls -al $ANDROID_SDK_ROOT - if [ ! -f $ANDROID_SDK_ROOT/emulator ]; then exit 1 fi - if [ ! -f $ANDROID_SDK_ROOT/build-tools ]; then exit 1 fi - if [ ! -f $ANDROID_SDK_ROOT/patcher ]; then exit 1 fi - if [ ! -f $ANDROID_SDK_ROOT/extras ]; then exit 1 fi - if [ ! -f $ANDROID_SDK_ROOT/platforms ]; then exit 1 fi - if [ ! -f $ANDROID_SDK_ROOT/platform-tools ]; then exit 1 fi - if [ ! -f $ANDROID_SDK_ROOT/system-images ]; then exit 1 fi + if [ ! -d $ANDROID_SDK_ROOT/emulator ]; then exit 1; fi + if [ ! -d $ANDROID_SDK_ROOT/build-tools ]; then exit 1; fi + if [ ! -d $ANDROID_SDK_ROOT/patcher ]; then exit 1; fi + if [ ! -d $ANDROID_SDK_ROOT/extras ]; then exit 1; fi + if [ ! -d $ANDROID_SDK_ROOT/platforms ]; then exit 1; fi + if [ ! -d $ANDROID_SDK_ROOT/platform-tools ]; then exit 1; fi + if [ ! -d $ANDROID_SDK_ROOT/system-images ]; then exit 1; fi - name: Ensure that the path is correct and installed programs are runnable shell: bash -l {0} @@ -70,5 +71,12 @@ jobs: export JAVA_HOME=$JAVA_HOME_11_X64 export ANDROID_SDK_ROOT=$NEW_ANDROID_SDK_ROOT echo "New SDK root $ANDROID_SDK_ROOT" - source setup/activate_native.sh $ANDROID_SDK_ROOT/emulator/emulator -list-avds + + - name: Ensure that the path is correct and the project can be activated + shell: bash -l {0} + run: | + export JAVA_HOME=$JAVA_HOME_11_X64 + export ANDROID_SDK_ROOT=$NEW_ANDROID_SDK_ROOT + echo "New SDK root $ANDROID_SDK_ROOT" + source setup/activate_native.sh diff --git a/setup/prereq_android_sdk_install.sh b/setup/prereq_android_sdk_install.sh index 5ed48f8c8..206b42add 100644 --- a/setup/prereq_android_sdk_install.sh +++ b/setup/prereq_android_sdk_install.sh @@ -32,7 +32,9 @@ echo "Downloading the android SDK. This will take a LONG time and will require y read -p "Do you wish to continue? (Y/N)" CONTINUE if [ $CONTINUE == "Y" ]; then + echo "BEGIN: About to start android SDK download" $ANDROID_SDK_ROOT/cmdline-tools/latest/bin/sdkmanager --package_file=setup/android_sdk_packages + echo "END: Done with android SDK download, exiting script" else echo "Please install this before proceeding with the installation steps" exit 1 From cf72cc9f51715b786850e3360d7fc95e4759e79d Mon Sep 17 00:00:00 2001 From: "K. Shankari" Date: Thu, 7 Apr 2022 21:54:32 -0700 Subject: [PATCH 152/175] Update packages and bump up version numbers - Update the sync plugin so that it doesn't run in a separate process - Update the local notification plugin so that it doesn't crash on startup if the screen is locked Both of these are tracked in https://github.com/e-mission/e-mission-docs/issues/712 --- config.cordovabuild.xml | 2 +- package.cordovabuild.json | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/config.cordovabuild.xml b/config.cordovabuild.xml index efb5b760d..051514feb 100644 --- a/config.cordovabuild.xml +++ b/config.cordovabuild.xml @@ -1,5 +1,5 @@ - + emission A commute pattern tracker and carbon footprint estimator. diff --git a/package.cordovabuild.json b/package.cordovabuild.json index 652fa1411..e30ebc8c1 100644 --- a/package.cordovabuild.json +++ b/package.cordovabuild.json @@ -1,6 +1,6 @@ { "name": "edu.berkeley.eecs.emission", - "version": "3.2.1", + "version": "3.2.2", "displayName": "emission", "license": "BSD-3-Clause", "repository": { @@ -81,7 +81,7 @@ "cordova-plugin-em-datacollection": "git+https://github.com/e-mission/e-mission-data-collection.git#v1.7.1", "cordova-plugin-em-jwt-auth": "git+https://github.com/e-mission/cordova-jwt-auth.git#v1.6.5", "cordova-plugin-em-server-communication": "git+https://github.com/e-mission/cordova-server-communication.git#v1.2.3", - "cordova-plugin-em-serversync": "git+https://github.com/e-mission/cordova-server-sync.git#v1.2.7", + "cordova-plugin-em-serversync": "git+https://github.com/e-mission/cordova-server-sync.git#v1.2.8", "cordova-plugin-em-settings": "git+https://github.com/e-mission/cordova-connection-settings.git#v1.2.2", "cordova-plugin-em-transition-notify": "git+https://github.com/e-mission/e-mission-transition-notify.git#v1.2.6", "cordova-plugin-em-unifiedlogger": "git+https://github.com/e-mission/cordova-unified-logger.git#v1.3.5", @@ -92,7 +92,7 @@ "cordova-plugin-ionic": "5.5.1", "cordova-plugin-ionic-keyboard": "2.2.0", "cordova-plugin-ionic-webview": "5.0.0", - "cordova-plugin-local-notification": "0.9.0-beta.3", + "cordova-plugin-local-notification": "https://github.com/timkellypa/cordova-plugin-local-notifications.git#083ccca0f4eee8fbec0cde1edd32207c286d2a04", "cordova-plugin-x-socialsharing": "6.0.3", "fs-extra": "^9.0.1", "klaw-sync": "^6.0.0", From 16876d0b2ca6d6cc85ccfd783ddfbbd626012960 Mon Sep 17 00:00:00 2001 From: "K. Shankari" Date: Mon, 25 Apr 2022 10:46:29 -0700 Subject: [PATCH 153/175] Upgrade leaflet to the most recent 1.8.0 Since we are fixing maps anyway, there's no need to stick with an obsolete version. The change is fairly straightforward - I don't think we were using a lot of the complex functionality in leaflet This is also installing a directly downloaded version instead of downloading from a package manager, so should be smaller. The only regression seems to be in events generated after the map has been unloaded, in which case it doesn't have any bounds and our `console.log` fails. We catch the `ValueError` error generated in that case and ignore it. ``` in mapEvents, event = "leafletDirectiveMap.detail.unload" leafletEvent = "unload" leafletObject is undefined in mapEvents, event = "leafletDirectiveMap.detail.zoomlevelschange" leafletEvent = "zoomlevelschange" leafletObject is undefined in mapEvents, event = "leafletDirectiveMap.detail.layerremove" leafletEvent = "layerremove" leafletObject is undefined ``` --- www/index.html | 4 +- www/js/diary/detail.js | 16 +- www/manual_lib/leaflet/.bower.json | 34 - www/manual_lib/leaflet/CHANGELOG.md | 957 -- www/manual_lib/leaflet/CONTRIBUTING.md | 155 - www/manual_lib/leaflet/Jakefile.js | 48 - www/manual_lib/leaflet/LICENSE | 23 - www/manual_lib/leaflet/PLUGIN-GUIDE.md | 127 - www/manual_lib/leaflet/README.md | 34 - www/manual_lib/leaflet/bower.json | 23 - www/manual_lib/leaflet/component.json | 20 - .../leaflet/dist/images/layers-2x.png | Bin 2898 -> 0 bytes www/manual_lib/leaflet/dist/images/layers.png | Bin 1502 -> 0 bytes .../leaflet/dist/images/marker-icon-2x.png | Bin 4033 -> 0 bytes .../leaflet/dist/images/marker-icon.png | Bin 1747 -> 0 bytes .../leaflet/dist/images/marker-shadow.png | Bin 797 -> 0 bytes www/manual_lib/leaflet/dist/leaflet-src.js | 9183 ---------- www/manual_lib/leaflet/dist/leaflet.js | 9 - www/manual_lib/leaflet/images/layers-2x.png | Bin 0 -> 1259 bytes www/manual_lib/leaflet/images/layers.png | Bin 0 -> 696 bytes .../leaflet/images/marker-icon-2x.png | Bin 0 -> 2464 bytes www/manual_lib/leaflet/images/marker-icon.png | Bin 0 -> 1466 bytes .../leaflet/images/marker-shadow.png | Bin 0 -> 618 bytes www/manual_lib/leaflet/leaflet-src.esm.js | 14033 +++++++++++++++ www/manual_lib/leaflet/leaflet-src.esm.js.map | 1 + www/manual_lib/leaflet/leaflet-src.js | 14126 ++++++++++++++++ www/manual_lib/leaflet/leaflet-src.js.map | 1 + www/manual_lib/leaflet/{dist => }/leaflet.css | 330 +- www/manual_lib/leaflet/leaflet.js | 6 + www/manual_lib/leaflet/leaflet.js.map | 1 + www/manual_lib/leaflet/package.json | 19 - 31 files changed, 28437 insertions(+), 10713 deletions(-) delete mode 100644 www/manual_lib/leaflet/.bower.json delete mode 100644 www/manual_lib/leaflet/CHANGELOG.md delete mode 100644 www/manual_lib/leaflet/CONTRIBUTING.md delete mode 100644 www/manual_lib/leaflet/Jakefile.js delete mode 100644 www/manual_lib/leaflet/LICENSE delete mode 100644 www/manual_lib/leaflet/PLUGIN-GUIDE.md delete mode 100644 www/manual_lib/leaflet/README.md delete mode 100644 www/manual_lib/leaflet/bower.json delete mode 100644 www/manual_lib/leaflet/component.json delete mode 100644 www/manual_lib/leaflet/dist/images/layers-2x.png delete mode 100644 www/manual_lib/leaflet/dist/images/layers.png delete mode 100644 www/manual_lib/leaflet/dist/images/marker-icon-2x.png delete mode 100644 www/manual_lib/leaflet/dist/images/marker-icon.png delete mode 100644 www/manual_lib/leaflet/dist/images/marker-shadow.png delete mode 100644 www/manual_lib/leaflet/dist/leaflet-src.js delete mode 100644 www/manual_lib/leaflet/dist/leaflet.js create mode 100644 www/manual_lib/leaflet/images/layers-2x.png create mode 100644 www/manual_lib/leaflet/images/layers.png create mode 100644 www/manual_lib/leaflet/images/marker-icon-2x.png create mode 100644 www/manual_lib/leaflet/images/marker-icon.png create mode 100644 www/manual_lib/leaflet/images/marker-shadow.png create mode 100644 www/manual_lib/leaflet/leaflet-src.esm.js create mode 100644 www/manual_lib/leaflet/leaflet-src.esm.js.map create mode 100644 www/manual_lib/leaflet/leaflet-src.js create mode 100644 www/manual_lib/leaflet/leaflet-src.js.map rename www/manual_lib/leaflet/{dist => }/leaflet.css (52%) create mode 100644 www/manual_lib/leaflet/leaflet.js create mode 100644 www/manual_lib/leaflet/leaflet.js.map delete mode 100644 www/manual_lib/leaflet/package.json diff --git a/www/index.html b/www/index.html index 8094d7466..aecd7d0a0 100644 --- a/www/index.html +++ b/www/index.html @@ -13,7 +13,7 @@ - + @@ -45,7 +45,7 @@ - + diff --git a/www/js/diary/detail.js b/www/js/diary/detail.js index efcd6bf67..2da16e74e 100644 --- a/www/js/diary/detail.js +++ b/www/js/diary/detail.js @@ -27,9 +27,19 @@ angular.module('emission.main.diary.detail',['ui-leaflet', 'ng-walkthrough', for (var k in mapEvents) { var eventName = 'leafletDirectiveMap.detail.' + mapEvents[k]; $scope.$on(eventName, function(event, data){ - console.log("in mapEvents, event = "+JSON.stringify(event.name)+ - " leafletEvent = "+JSON.stringify(data.leafletEvent.type)+ - " leafletObject = "+JSON.stringify(data.leafletObject.getBounds())); + try { + console.log("in mapEvents, event = "+JSON.stringify(event.name)+ + " leafletEvent = "+JSON.stringify(data.leafletEvent.type)+ + " leafletObject = "+JSON.stringify(data.leafletObject.getBounds())); + } catch (e) { + if (e instanceof TypeError) { + console.log("in mapEvents, event = "+JSON.stringify(event.name)+ + " leafletEvent = "+JSON.stringify(data.leafletEvent.type)+ + " leafletObject is undefined"); + } else { + console.log(e); + } + } $scope.eventDetected = event.name; }); } diff --git a/www/manual_lib/leaflet/.bower.json b/www/manual_lib/leaflet/.bower.json deleted file mode 100644 index f58a99ddd..000000000 --- a/www/manual_lib/leaflet/.bower.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "name": "leaflet", - "version": "0.7.7", - "description": "JavaScript library for mobile-friendly interactive maps", - "main": [ - "dist/leaflet.css", - "dist/leaflet-src.js", - "dist/images/layers-2x.png", - "dist/images/layers.png", - "dist/images/marker-icon-2x.png", - "dist/images/marker-icon.png", - "dist/images/marker-shadow.png" - ], - "ignore": [ - ".*", - "CHANGELOG.json", - "FAQ.md", - "debug", - "spec", - "src", - "build" - ], - "homepage": "https://github.com/Leaflet/Leaflet", - "_release": "0.7.7", - "_resolution": { - "type": "version", - "tag": "v0.7.7", - "commit": "197f9d43b7bbc73c0492bf62cd666a5a98038098" - }, - "_source": "git://github.com/Leaflet/Leaflet.git", - "_target": "^0.7.7", - "_originalSource": "leaflet", - "_direct": true -} \ No newline at end of file diff --git a/www/manual_lib/leaflet/CHANGELOG.md b/www/manual_lib/leaflet/CHANGELOG.md deleted file mode 100644 index d10e6188f..000000000 --- a/www/manual_lib/leaflet/CHANGELOG.md +++ /dev/null @@ -1,957 +0,0 @@ -Leaflet Changelog -================= - -(all changes without author notice are by [@mourner](https://github.com/mourner)) - -## 0.7.7 (October 26, 2015) - -* Fixed a regression that could sometimes cause tiles to disappear when pinch-zooming on iOS devices. -* Fixed a regression related to msPointer detection in IE10 (affecting Leaflet.draw and some other plugins) (by @danzel) #3842 #3839 #3804 -* Fixed a bug where a mouseout could fire after a vector element was removed (by @sambernet). #3849 #3829 -* Fixed touch interactions in Edge browser (by @mitchless & @Neorth). #3853 #3379 -* Fixed a bug where removing a layer group from a feature group would throw an error (by @Lambdac0re). #3869 - -Note tha we skipped 0.7.6 version for which we accidentally published a broken build to NPM. - -## 0.7.5 (September 2, 2015) - -* Fixed a regression that broke animation in Leaflet.markercluster. [#3796](https://github.com/Leaflet/Leaflet/issues/3796) - -## 0.7.4 (September 1, 2015) - -* Fixed a bug introduced by a recent Chrome update that caused the map not to react to interactions until all tiles are loaded. [#3689](https://github.com/Leaflet/Leaflet/issues/3689) -* Fixed a bug where tile layers were not respecting their `minZoom` or `maxZoom` options (by [@ivansanchez](https://github.com/ivansanchez)) [#3778](https://github.com/Leaflet/Leaflet/pull/3778) -* Improved detection of touch-capable web browsers, in particular fixing touch interactions in device emulation mode in Chrome and Firefox (by [@ivansanchez](https://github.com/ivansanchez)) [#3520](https://github.com/Leaflet/Leaflet/pull/3520) [#3710](https://github.com/Leaflet/Leaflet/pull/3710) -* Fixed a bug where tile layers with `maxNativeZoom` were not checking bounds properly (by [@jlaxon](https://github.com/jlaxon)) [#3415](https://github.com/Leaflet/Leaflet/pull/3152) -* Fixed a bug where popups were not remembering which layer originated them after calling `bindPopup(popup)` (by [@Eschon](https://github.com/Eschon)) [#3675](https://github.com/Leaflet/Leaflet/pull/3765) -* Fixed a race condition between markers and zoom animation (by [@perliedman](https://github.com/perliedman)) [#3152](https://github.com/Leaflet/Leaflet/pull/3152) -* Fixed a bug with `Map.fitBounds` padding (by [@bsstoner](https://github.com/bsstoner)). [#2489](https://github.com/Leaflet/Leaflet/issues/2489) -* Allow canvas paths to fire `dblclick` and `contextmenu` events (by [@ivansanchez](https://github.com/ivansanchez)) [#3482](https://github.com/Leaflet/Leaflet/pull/3482) -* Allow canvas filled polygons to use the `fillRule` option (by [@w8r](https://github.com/w8r)) [#3477](https://github.com/Leaflet/Leaflet/pull/3477) -* Allow canvas lines to use `lineCap` and `lineJoin` options (by [@northerneyes](https://github.com/northerneyes)) [#3156](https://github.com/Leaflet/Leaflet/pull/3156) -* Updated bower definitions to comply with best practices (by [@guptaso2](https://github.com/guptaso2)) [#2726](https://github.com/Leaflet/Leaflet/pull/2726) [#3448](https://github.com/Leaflet/Leaflet/pull/3448) - -## 0.7.3 (May 23, 2014) - -* Added proper **bower** and **component** support (by [@calvinmetcalf](https://github.com/calvinmetcalf)). [#2561](https://github.com/Leaflet/Leaflet/pull/2561) [#1903](https://github.com/Leaflet/Leaflet/issues/1903) -* Fixed a bug where dragging the map outside the window caused an error on FF. [#2610](https://github.com/Leaflet/Leaflet/issues/2610) -* Fixed a bug where some taps on Android where not working, often falsely perceived as drags (by [@axefrog](https://github.com/axefrog)). [#2503](https://github.com/Leaflet/Leaflet/pull/2503) -* Fixed a bug where tapping too quickly on Android ignored most taps. [#2303](https://github.com/Leaflet/Leaflet/issues/2303) -* Fixed a bug where calling `setView` (or similar methods) several times in succession could freeze the map. [#2521](https://github.com/Leaflet/Leaflet/issues/2521) [#2236](https://github.com/Leaflet/Leaflet/issues/2236) [#2485](https://github.com/Leaflet/Leaflet/issues/2485) -* Fixed a bug where `Control.Layers` wasn't properly removed (by [@jack-kerouac](https://github.com/jack-kerouac)). [#2569](https://github.com/Leaflet/Leaflet/pull/2569) -* Fixed a bug that caused `TileLayer` `load` event not to fire properly. [#2510](https://github.com/Leaflet/Leaflet/issues/2510) -* Fixed Canvas-based paths not triggering `remove` event when removed (by @adimitrov). [#2486](https://github.com/Leaflet/Leaflet/pull/2486) -* Fixed a bug where you could end up with fractional zoom after pinch-zooming in some cases (by [@danzel](https://github.com/danzel). [#2400](https://github.com/Leaflet/Leaflet/pull/2400) [#1943](https://github.com/Leaflet/Leaflet/issues/1934) - -## 0.7.2 (January 17, 2013) - -* Fixed a bug that appeared with **Chrome 32 update** that made all **mouse events shifted on scrolled pages**. [#2352](https://github.com/Leaflet/Leaflet/issues/2352) -* Fixed a bug that could break tile loading when using non-standard tile sizes. [#2288](https://github.com/Leaflet/Leaflet/issues/2288) -* Fixed a bug where `maxNativeZoom` option didn't work with TMS tile layers (by [@perliedman](https://github.com/perliedman)). [#2321](https://github.com/Leaflet/Leaflet/issues/2321) [#2314](https://github.com/Leaflet/Leaflet/issues/2314) - -## 0.7.1 (December 6, 2013) - -* Fixed a bug where pinch-zooming quickly could occasionally leave the map at a fractional zoom thus breaking tile loading (by [@danzel](https://github.com/danzel)). [#2269](https://github.com/Leaflet/Leaflet/pull/2269) [#2255](https://github.com/Leaflet/Leaflet/issues/2255) [#1934](https://github.com/Leaflet/Leaflet/issues/1934) -* Fixed tile flickering issues on some old Android 2/3 devices by disabling buggy hardware accelerated CSS there (by [@danzel](https://github.com/danzel)). [#2216](https://github.com/Leaflet/Leaflet/pull/2216) [#2198](https://github.com/Leaflet/Leaflet/issues/2198) -* Fixed a regression that sometimes led to an error when you started pinch-zoom as the first action on the map (by [@danzel](https://github.com/danzel)). [#2259](https://github.com/Leaflet/Leaflet/pull/2259) [#2256](https://github.com/Leaflet/Leaflet/issues/2256) -* Reverted `L.Util.template` optimizations to allow Leaflet to be used in eval-banning environments like browser extensions (performance gain was insignificant anyway) (by [@calvinmetcalf](https://github.com/calvinmetcalf)). [#2217](https://github.com/Leaflet/Leaflet/issues/2217) [#2209](https://github.com/Leaflet/Leaflet/issues/2209) [#1968](https://github.com/Leaflet/Leaflet/issues/1968) -* Fixed a regression where `Map` `invalidateSize` could lead to unexpected results when called before map initialization (by [@Zverik](https://github.com/Zverik)). [#2250](https://github.com/Leaflet/Leaflet/issues/2250) [#2249](https://github.com/Leaflet/Leaflet/issues/2249) -* Fixed a regression where `FeatureGroup` containing other group overwrote original `e.layer` value in mouse events (by [@gumballhead](https://github.com/gumballhead)). [#2253](https://github.com/Leaflet/Leaflet/pull/2253) [#2252](https://github.com/Leaflet/Leaflet/issues/2252) -* Fixed a regression where `CircleMarker` `setLatLngs` didn't return `this` (by [@radicalbiscuit](https://github.com/radicalbiscuit)). [#2206](https://github.com/Leaflet/Leaflet/pull/2206) - -## 0.7 (November 18, 2013) - -### Improvements - -#### Usability improvements - -* Added **support for IE11 touch devices** (by [@danzel](https://github.com/danzel), [@DanielX2](https://github.com/DanielX2) and [@fnicollet](https://github.com/fnicollet)). [#2039](https://github.com/Leaflet/Leaflet/pull/2039) [#2066](https://github.com/Leaflet/Leaflet/pull/2066) [#2037](https://github.com/Leaflet/Leaflet/issues/2037) [#2102](https://github.com/Leaflet/Leaflet/issues/2102) -* Added shift-double-click to zoom out shortcut. [#2185](https://github.com/Leaflet/Leaflet/issues/2185) -* Significantly improved **controls design on mobile** devices. [#1868](https://github.com/Leaflet/Leaflet/issues/1868) [#2012](https://github.com/Leaflet/Leaflet/issues/2012) -* Fixed and improved IE7-8 control and popup styles. -* Made subtle improvements to control styles on desktop browsers. -* Improved keyboard nav support so that map doesn't loose focus when you click on a control (by [@jacobtoye](https://github.com/jacobtoye)). [#2150](https://github.com/Leaflet/Leaflet/issues/2150) [#2148](https://github.com/Leaflet/Leaflet/issues/2148) -* Improved `maxBounds` behavior: now it doesn't force higher minimal zoom, and anchors to max bounds edges properly when zooming (by [@kapouer](https://github.com/kapouer) and [@mourner](https://github.com/mourner)). [#2187](https://github.com/Leaflet/Leaflet/pull/2187) [#1946](https://github.com/Leaflet/Leaflet/pull/1946) [#2081](https://github.com/Leaflet/Leaflet/issues/2081) [#2168](https://github.com/Leaflet/Leaflet/issues/2168) [#1908](https://github.com/Leaflet/Leaflet/issues/1908) - -#### Map API improvements - -* Made `Map` `setView` `zoom` argument optional. [#2056](https://github.com/Leaflet/Leaflet/issues/2056) -* Added `maxZoom` option to `Map` `fitBounds`. [#2101](https://github.com/Leaflet/Leaflet/issues/2101) -* Added `Map` `bounceAtZoomLimits` option that makes the map bounce when you pinch-zoom past limits (it worked like this before, but now you can disable this) (by [@trevorpowell](https://github.com/trevorpowell)). [#1864](https://github.com/Leaflet/Leaflet/issues/1864) [#2072](https://github.com/Leaflet/Leaflet/pull/2072) -* Added `distance` property to `Map` and `Marker` `dragend` events. [#2158](https://github.com/Leaflet/Leaflet/issues/2158) [#872](https://github.com/Leaflet/Leaflet/issues/872) -* Added optional support for center-oriented scroll and double-click zoom (by [@jfirebaugh](https://github.com/jfirebaugh)). [#1939](https://github.com/Leaflet/Leaflet/issues/1939) -* Added `timestamp` to `Map` `locationfound` event. [#584](https://github.com/Leaflet/Leaflet/pull/584) -* Improved `Map` `invalidateSize` to call `moveend` immediately unless given `debounceMoveend: true` option (by [@jfirebaugh](https://github.com/jfirebaugh)). [#2181](https://github.com/Leaflet/Leaflet/issues/2181) - -#### TileLayer API improvements - -* Added `TileLayer` `maxNativeZoom` option that allows displaying tile layers on zoom levels above their maximum by **upscaling tiles**. [#1802](https://github.com/Leaflet/Leaflet/issues/1802) [#1798](https://github.com/Leaflet/Leaflet/issues/1798) -* Added `TileLayer` `tileloadstart` event (by [@tmcw](https://github.com/tmcw)). [#2142](https://github.com/Leaflet/Leaflet/pull/2142) [#2140](https://github.com/Leaflet/Leaflet/issues/2140) -* Improved `TileLayer` world size (used for wrapping and limiting tiles) to be derived from CRS instead of hardcoded, making it easier to use with custom projections (by [@perliedman](https://github.com/perliedman)). [#2160](https://github.com/Leaflet/Leaflet/pull/2160) - -#### Marker API improvements - -* Added CSS classes to draggable markers for easier customization (by [@snkashis](https://github.com/snkashis)). [#1902](https://github.com/Leaflet/Leaflet/issues/1902) [#1916](https://github.com/Leaflet/Leaflet/issues/1916) -* Added `Marker` `add` event (by [@tohaocean](https://github.com/tohaocean)). [#1942](https://github.com/Leaflet/Leaflet/issues/1942) -* Added `Marker` `getPopup` method (by [@scottharvey](https://github.com/scottharvey)). [#618](https://github.com/Leaflet/Leaflet/issues/618) [#1197](https://github.com/Leaflet/Leaflet/pull/1197) -* Added `Marker` `alt` option for adding `alt` text to markers (by [@jimmytidey](https://github.com/jimmytidey)). [#2112](https://github.com/Leaflet/Leaflet/pull/2112) - -#### Vector layers API improvements - -* Added `Path` `className` option for adding custom class names to vector layers. -* Added `Path` `lineCap` and `lineJoin` options (by [@palewire](https://github.com/palewire)). [#1843](https://github.com/Leaflet/Leaflet/issues/1843) [#1863](https://github.com/Leaflet/Leaflet/issues/1863) [#1881](https://github.com/Leaflet/Leaflet/issues/1881) -* Added ability to pass vector options to `GeoJSON` (by [@kapouer](https://github.com/kapouer)). [#2075](https://github.com/Leaflet/Leaflet/pull/2075) -* Improved `Polygon` `setLatLngs` to also accept holes (by [@aparshin](https://github.com/aparshin)). [#2095](https://github.com/Leaflet/Leaflet/pull/2095) [#1518](https://github.com/Leaflet/Leaflet/issues/1518) -* Added `GeoJSON` 3D format support and optional `altitude` argument to `LatLng` constructor (by [@Starefossen](https://github.com/Starefossen)). [#1822](https://github.com/Leaflet/Leaflet/pull/1822) -* Added `MultiPolygon` and `MultiPolyline` `openPopup` method. [#2046](https://github.com/Leaflet/Leaflet/issues/2046) - -#### Popup API improvements - -* Added `Popup` `update` method. [#1959](https://github.com/Leaflet/Leaflet/issues/1959) -* Added `Popup` `autoPanPaddingTopLeft` and `autoPanPaddingBottomRight` options (by [@albburtsev](https://github.com/albburtsev)). [#1972](https://github.com/Leaflet/Leaflet/issues/1972) [#1588](https://github.com/Leaflet/Leaflet/issues/1588) -* Added `Popup` `getContent` method. [#2100](https://github.com/Leaflet/Leaflet/issues/2100) -* Added `Popup` `getLatLng` method (by [@AndreyGeonya](https://github.com/AndreyGeonya)). [#2097](https://github.com/Leaflet/Leaflet/pull/2097) - -#### Misc API improvements - -* Added `ImageOverlay` `setUrl` and `getAttribution` methods and `attribution` option (by [@stsydow](https://github.com/stsydow)). [#1957](https://github.com/Leaflet/Leaflet/issues/1957) [#1958](https://github.com/Leaflet/Leaflet/issues/1958) -* Added localization support for the zoom control (by [@Danielku15](https://github.com/Danielku15)). [#1953](https://github.com/Leaflet/Leaflet/issues/1953) [#1643](https://github.com/Leaflet/Leaflet/issues/1643) [#1953](https://github.com/Leaflet/Leaflet/pull/1953) -* Significantly improved `L.Util.template` performance (affects `L.TileLayer`) by introducing cached template compilation (by [@calvinmetcalf](https://github.com/calvinmetcalf)). [#1969](https://github.com/Leaflet/Leaflet/issues/1969) [#1968](https://github.com/Leaflet/Leaflet/issues/1968) [#1554](https://github.com/Leaflet/Leaflet/issues/1554) -* Added `CRS` `getSize` for getting the world size in pixels (by [@perliedman](https://github.com/perliedman)). [#2160](https://github.com/Leaflet/Leaflet/pull/2160) -* Added `leaflet-drag-target` CSS class to an element under cursor when dragging for more flexible customization. [#2164](https://github.com/Leaflet/Leaflet/issues/2164) [#1902](https://github.com/Leaflet/Leaflet/issues/1902) -* Improved `L.DomUtil` `addClass`, `removeClass`, `hasClass` methods performance and fixed it to work with SVG elements. [#2164](https://github.com/Leaflet/Leaflet/issues/2164) - -#### Dev workflow improvements - -* Added an [official FAQ](https://github.com/Leaflet/Leaflet/blob/master/FAQ.md). -* Cleaned up and moved old IE styles to `leaflet.css` and removed `leaflet.ie.css`, so **no need for IE conditional comment** when including Leaflet now. [#2159](https://github.com/Leaflet/Leaflet/issues/2159) -* Added `leaflet-oldie` CSS class to map container in IE7-8 for easier styling. [#2159](https://github.com/Leaflet/Leaflet/issues/2159) -* Officially **dropped support for IE6**. Nobody cares anyway, and Leaflet should still be accessible on it. [#2159](https://github.com/Leaflet/Leaflet/issues/2159) -* Improved the build system to check JS errors in spec files. [#2151](https://github.com/Leaflet/Leaflet/issues/2151) -* Fixed `jake` command to run tests before building the source. [#2151](https://github.com/Leaflet/Leaflet/issues/2151) -* Switched the main file in `package.json` to unminified version for NPM/Browserify (by [@icetan](https://github.com/icetan)). [#2109](https://github.com/Leaflet/Leaflet/pull/2109) - -### Bugfixes - -#### 0.6 regression fixes - -* Fixed a **memory leak in iOS7** that could crash Safari when handling lots of objects (e.g. 1000 markers) (by [@danzel](https://github.com/danzel)). [#2149](https://github.com/Leaflet/Leaflet/pull/2149) [#2122](https://github.com/Leaflet/Leaflet/issues/2122) -* Fixed a bug that caused lag at the beginning of panning in Chrome (by [@jfirebaugh](https://github.com/jfirebaugh)). [#2163](https://github.com/Leaflet/Leaflet/issues/2163) -* Fixed a regression that made the layers control unscrollable in Firefox. [#2029](https://github.com/Leaflet/Leaflet/issues/2029) -* Fixed a regression that broke `worldCopyJump: true` option (by [@fastrde](https://github.com/fastrde)). [#1904](https://github.com/Leaflet/Leaflet/issues/1904) [#1831](https://github.com/Leaflet/Leaflet/issues/1831) [#1982](https://github.com/Leaflet/Leaflet/issues/1982) -* Fixed a regression where a first map click after popup close button click was ignored (by [@fastrde](https://github.com/fastrde)). [#1537](https://github.com/Leaflet/Leaflet/issues/1537) [#1963](https://github.com/Leaflet/Leaflet/issues/1963) [#1925](https://github.com/Leaflet/Leaflet/issues/1925) -* Fixed a regression where `L.DomUtil.getMousePosition` would throw an error if container argument not provided (by [@scooterw](https://github.com/scooterw)). [#1826](https://github.com/Leaflet/Leaflet/issues/1826) [#1928](https://github.com/Leaflet/Leaflet/issues/1928) [#1926](https://github.com/Leaflet/Leaflet/issues/1926) -* Fixed a regression with vector layers positioning when zooming on IE10+ touch devices (by [@danzel](https://github.com/danzel)). [#2002](https://github.com/Leaflet/Leaflet/issues/2002) [#2000](https://github.com/Leaflet/Leaflet/issues/2000) -* Fixed a regression with `maxBounds` behaving weirdly on panning inertia out of bounds. [#2168](https://github.com/Leaflet/Leaflet/issues/2168) - -#### General bugfixes - -* Fixed a bug where the map could freeze if centered and immediately recentered on initialization. [#2071](https://github.com/Leaflet/Leaflet/issues/2071) -* Fixed a bug where all maps except the first one on a page didn't track window resize. [#1980](https://github.com/Leaflet/Leaflet/issues/1980) -* Fixed a bug where tiles in `EPSG:3395` projection were shifted (by [@aparshin](https://github.com/aparshin)). [#2020](https://github.com/Leaflet/Leaflet/issues/2020) -* Fixed a bug where scale control displayed wrong scale when on pages with `box-sizing: border-box`. -* Fixed a bug where zoom control button didn't appear as disabled if map was initialized at the zoom limit. [#2083](https://github.com/Leaflet/Leaflet/issues/2083) -* Fixed a bug where box zoom also triggered a map click event (by [@fastrde](https://github.com/fastrde)). [#1951](https://github.com/Leaflet/Leaflet/issues/1951) [#1884](https://github.com/Leaflet/Leaflet/issues/1884) -* Fixed a bug where shift-clicking on a map immediately after a drag didn't trigger a click event (by [@fastrde](https://github.com/fastrde)). [#1952](https://github.com/Leaflet/Leaflet/issues/1952) [#1950](https://github.com/Leaflet/Leaflet/issues/1950) -* Fixed a bug where content was updated twice when opening a popup. [#2137](https://github.com/Leaflet/Leaflet/issues/2137) -* Fixed a bug that could sometimes cause infinite panning loop when using `maxBounds` (by [@kapouer](https://github.com/kapouer) and [@mourner](https://github.com/mourner)). [#2187](https://github.com/Leaflet/Leaflet/pull/2187) [#1946](https://github.com/Leaflet/Leaflet/pull/1946) [#2081](https://github.com/Leaflet/Leaflet/issues/2081) [#2168](https://github.com/Leaflet/Leaflet/issues/2168) [#1908](https://github.com/Leaflet/Leaflet/issues/1908) - -#### Browser bugfixes - -* Fixed a bug where keyboard `+` no longer zoomed the map on FF 22+ (by [@fastrde](https://github.com/fastrde)). [#1943](https://github.com/Leaflet/Leaflet/issues/1943) [#1981](https://github.com/Leaflet/Leaflet/issues/1981) -* Fixed a bug where calling `Map` `remove` throwed an error in IE6-8. [#2015](https://github.com/Leaflet/Leaflet/issues/2015) -* Fixed a bug where `isArray` didn't work in rare cases in IE9. [#2077](https://github.com/Leaflet/Leaflet/issues/2077) -* Fixed a bug where FF sometimes produced console warnings when animating markers. [#2090](https://github.com/Leaflet/Leaflet/issues/2090) -* Fixed a bug where mouse wasn't handled correctly on RTL pages in some cases (by [@danzel](https://github.com/danzel)). [#1986](https://github.com/Leaflet/Leaflet/issues/1986) [#2136](https://github.com/Leaflet/Leaflet/pull/2136) - -#### Mobile bugfixes - -* Fixed a bug where tiles could **disappear after zooming on Chrome 30+ for Android** (by [@danzel](https://github.com/danzel)). [#2152](https://github.com/Leaflet/Leaflet/pull/2152) [#2078](https://github.com/Leaflet/Leaflet/issues/2078) -* Fixed a bug on IE10+ touch where pinch-zoom also caused click (by [@danzel](https://github.com/danzel)). [#2117](https://github.com/Leaflet/Leaflet/pull/2117) [#2094](https://github.com/Leaflet/Leaflet/issues/2094) -* Fixed a bug on IE10+ touch where controls didn't loose the pressed state after tapping (by [@danzel](https://github.com/danzel)). [#2111](https://github.com/Leaflet/Leaflet/pull/2111) [#2103](https://github.com/Leaflet/Leaflet/issues/2103) -* Fixed a bug where clicking on layers control labels on iOS throwed an error (by [@olemarkus](https://github.com/olemarkus) and [@dagjomar](https://github.com/dagjomar)). [#1984](https://github.com/Leaflet/Leaflet/issues/1984) [#1989](https://github.com/Leaflet/Leaflet/issues/1989) - -#### Map API bugfixes - -* Fixed a bug where `Map` `getCenter` returned old result after map container size changed (by [@jfirebaugh](https://github.com/jfirebaugh)). [#1940](https://github.com/Leaflet/Leaflet/issues/1940) [#1919](https://github.com/Leaflet/Leaflet/issues/1919) -* Fixed `Map` `invalidateSize` rounding issues when changing map size by an odd pixel amount (by [@russelldavis](https://github.com/russelldavis)). [#1931](https://github.com/Leaflet/Leaflet/issues/1931) -* Fixed a bug where `Map` `removeLayer` didn't return `this` in a corner case (by [@jfirebaugh](https://github.com/jfirebaugh)). -* Fixed a bug where calling `Map` `setZoom` before `setView` would throw an error. [#1449](https://github.com/Leaflet/Leaflet/issues/1449) - -#### Layers API bugfixes - -* Fixed a bug where `Popup` `setLatLng` unnecessarily reset content and updated layout; works much faster now. [#2167](https://github.com/Leaflet/Leaflet/issues/2167) -* Fixed a bug where `toGeoJSON` of layers originated from GeoJSON GeometryCollection and MultiPoint didn't work properly (wasn't round-tripped). [#1956](https://github.com/Leaflet/Leaflet/issues/1956) -* Fixed `GeoJSON` dependencies in build configuration that could lead to a broken custom build in some situations (by [@alubchuk](https://github.com/alubchuk)). [#1909](https://github.com/Leaflet/Leaflet/issues/1909) -* Fixed a bug where `CircleMarker` popup placement wasn't updated after calling `setLatLng` (by [@snkashis](https://github.com/snkashis)). [#1921](https://github.com/Leaflet/Leaflet/issues/1921) [#1927](https://github.com/Leaflet/Leaflet/issues/1927) -* Fixed a bug where popup anchor wasn't updated on `Marker` `setIcon` (by [@snkashis](https://github.com/snkashis)). [#1874](https://github.com/Leaflet/Leaflet/issues/1874) [#1891](https://github.com/Leaflet/Leaflet/issues/1891) -* Fixed a bug with GeoJSON not throwing a descriptive error if a polygon has zero length inner ring (by [@snkashis](https://github.com/snkashis)). [#1917](https://github.com/Leaflet/Leaflet/issues/1917) [#1918](https://github.com/Leaflet/Leaflet/issues/1918) -* Fixed a bug where `FeatureGroup` would break when using non-evented children layers (by [@tmcw](https://github.com/tmcw)). [#2032](https://github.com/Leaflet/Leaflet/pull/2032) [#1962](https://github.com/Leaflet/Leaflet/issues/1962) -* Fixed a bug where `CircleMarker` `getRadius` would always return `null`. [#2016](https://github.com/Leaflet/Leaflet/issues/2016) [#2017](https://github.com/Leaflet/Leaflet/pull/2017) -* Fixed a bug where `TileLayer.WMS` didn't work with WMS 1.3 & EPSG4326 projection (by [@Bobboya](https://github.com/Bobboya)). [#1897](https://github.com/Leaflet/Leaflet/pull/1897) -* Fixed a bug where `FeatureGroup` events `e.layer` was sometimes empty in old IE. [#1938](https://github.com/Leaflet/Leaflet/issues/1938) - -#### Misc API bugfixes - -* Fixed a bug where `L.latLngBounds` didn't accept simple object `LatLng` form (by [@Gnurfos](https://github.com/Gnurfos)). [#2025](https://github.com/Leaflet/Leaflet/issues/2025) [#1915](https://github.com/Leaflet/Leaflet/issues/1915) -* Fixed a bug where `L.Util.tempalate` wouldn't work with double quotes in the string (by [@jieter](https://github.com/jieter)). [#1968](https://github.com/Leaflet/Leaflet/issues/1968) [#2121](https://github.com/Leaflet/Leaflet/pull/2121) [#2120](https://github.com/Leaflet/Leaflet/issues/2120) -* Fixed a bug where attribution control that was added to a map after attributed layers didn't have the corresponding attributions (by [@snkashis](https://github.com/snkashis)). [#2177](https://github.com/Leaflet/Leaflet/issues/2177) [#2178](https://github.com/Leaflet/Leaflet/pull/2178) - - -## 0.6.4 (July 25, 2013) - -* Fixed a regression where `fitBounds` and `setMaxBounds` could freeze the browser in some situations. [#1895](https://github.com/Leaflet/Leaflet/issues/1895) [1866](https://github.com/Leaflet/Leaflet/issues/1866) -* Fixed a bug where click on a map on a page with horizontal scroll caused the page to scroll right (by [@mstrelan](https://github.com/mstrelan)). [#1901](https://github.com/Leaflet/Leaflet/issues/1901) - -## 0.6.3 (July 17, 2013) - -### Regression fixes - -* Fixed a regression where mouse interaction had incorrect coordinates in some map positioning cases (by [@scooterw](https://github.com/scooterw)). [#1826](https://github.com/Leaflet/Leaflet/issues/1826) [#1684](https://github.com/Leaflet/Leaflet/issues/1684) [#1745](https://github.com/Leaflet/Leaflet/issues/1745) [#1](https://github.com/Leaflet/Leaflet/issues/1) -* Fixed a regression that prevented the map from responding to drag on areas covered with `ImageOverlay` (by [@jfirebaugh](https://github.com/jfirebaugh)). [#1821](https://github.com/Leaflet/Leaflet/issues/1821) -* Fixed a regression where `layerremove` and `layeradd` were fired before the corresponding action finishes (by [@jfirebaugh](https://github.com/jfirebaugh)). [#1846](https://github.com/Leaflet/Leaflet/issues/1846) -* Fixed a regression with `worldCopyJump: true` breaking the map on small zoom levels (by [@danzel](https://github.com/danzel)). [#1831](https://github.com/Leaflet/Leaflet/issues/1831) -* Fixed a regression where `Marker` shadow didn't animate on zoom after using `setIcon`. [#1768](https://github.com/Leaflet/Leaflet/issues/1768) -* Fixed a regression where the map would stuck when trying to animate zoom before any tile layers are added to the map. [#1484](https://github.com/Leaflet/Leaflet/issues/1484) [#1845](https://github.com/Leaflet/Leaflet/issues/1845) -* Fixed a regression with the layers control and popups closing on inside click in IE < 9. [#1850](https://github.com/Leaflet/Leaflet/issues/1850) -* Fixed a regression where scrolled popup content woudln't scroll in FF (by [@jfirebaugh](https://github.com/jfirebaugh)). - -### Bug fixes - -* Fixed vector feature flickering on Safari Mac for screen < 2000px. [#902](https://github.com/Leaflet/Leaflet/issues/902) -* Fixed a bug where `GeoJSON` ignored non-feature geometries passed in an array. [#1840](https://github.com/Leaflet/Leaflet/issues/1840) -* Fixed a bug where `Map` `minZoom` and `maxZoom` didn't always override values derived from the added tile layers. [1848](https://github.com/Leaflet/Leaflet/issues/1848) -* Fixed a bug where `TileLayer.Canvas` wasn't immediately redrawn when `redraw` is called (by [@tofferrosen](https://github.com/tofferrosen)). [#1797](https://github.com/Leaflet/Leaflet/issues/1797) [#1817](https://github.com/Leaflet/Leaflet/issues/1817) -* Fixed a bug where `FeatureGroup` still fired `layerremove` event on `removeLayer` even if the given layer wan't present in the group (by (by [@danzel](https://github.com/danzel))). [#1847](https://github.com/Leaflet/Leaflet/issues/1847) [#1858](https://github.com/Leaflet/Leaflet/issues/1858) -* Fixed a bug where `Marker` `setOpacity` wasn't returning the marker (by [@freepius44](https://github.com/freepius44)). [#1851](https://github.com/Leaflet/Leaflet/issues/1851) -* Fixed a bug where removing the map element from the DOM before panning transition has finished could keep a setInterval loop running forever (by [@rutkovsky](https://github.com/rutkovsky)). [#1825](https://github.com/Leaflet/Leaflet/issues/1825) [#1856](https://github.com/Leaflet/Leaflet/issues/1856) -* Fixed mobile styles to apply to `leaflet-bar` elements. - -### Improvements - -* Added ability to pass zoom/pan animation options to `setMaxBounds` (by [@davidjb](http://git.io/djb)). [#1834](https://github.com/Leaflet/Leaflet/pull/1834) -* Added `MultiPolyline` and `MultiPolygon` `getLatLngs` method. [#1839](https://github.com/Leaflet/Leaflet/issues/1839) - -### Dev Workflow improvements - -* Leaflet builds (*.js files in the `dist` folder) were removed from the repo and are now done automatically on each commit for `master` and `stable` branches by [Travis CI](travis-ci.org/Leaflet/Leaflet). The download links are on the [Leafet download page](http://leafletjs.com/download.html). - -## 0.6.2 (June 28, 2013) - - * Fixed a bug that caused wrong tile layers stacking order when using opacity < 1 (by [@jfirebaugh](https://github.com/jfirebaugh)). [#1804](https://github.com/Leaflet/Leaflet/issues/1804) [#1790](https://github.com/Leaflet/Leaflet/issues/1790) [#1667](https://github.com/Leaflet/Leaflet/issues/1667) - * Fixed a regression that caused tiles selection when double-clicking absolutely positioned maps with vector layers in it in Firefox (WTF!) (by [@jfirebaugh](https://github.com/jfirebaugh)). [#1807](https://github.com/Leaflet/Leaflet/issues/1807) - * Fixed a regression with a wrong cursor when dragging a map with vector layers, and tiles becoming selected on double click (by [@jfirebaugh](https://github.com/jfirebaugh)). [#1800](https://github.com/Leaflet/Leaflet/issues/1800) - * Fixed a regression that caused flickering of tiles near map border on zoom animation in Chrome. - -## 0.6.1 (June 27, 2013) - - * Fixed a regression with mouse wheel zooming too fast on Firefox (by [@jfirebaugh](https://github.com/jfirebaugh)). [#1788](https://github.com/Leaflet/Leaflet/issues/1788) - * Fixed a regression with broken zooming on maps with EPSG3395 projection. [#1796](https://github.com/Leaflet/Leaflet/issues/1796) - * Fixed a bug where zoom buttons inherited Bootstrap link hover styles. [#1791](https://github.com/Leaflet/Leaflet/issues/1791) - -## 0.6 (June 26, 2013) - -### Breaking changes - - * Moved polyline editing code into [Leaflet.draw](https://github.com/Leaflet/Leaflet.draw) plugin (where it fits much better along with all other editing and drawing handlers). The API remains the same. - * Dropped support for environments that augment `Object.prototype` (luckily it's a thing of the past nowadays). - * `Map` `invalidateSize` no longer fires `move` and `moveend` events if the map size didn't change. [#1819](https://github.com/Leaflet/Leaflet/issues/1819) - -### Improvements - -#### Usability and performance improvements - - * **Improved zoom control design** - cleaner, simpler, more accessible (mostly by [@jacobtoye](https://github.com/jacobtoye)). [#1313](https://github.com/Leaflet/Leaflet/issues/1313) - * Updated `Control.Layers` icon (designed by Volker Kinkelin), added retina version and SVG source. [#1739](https://github.com/Leaflet/Leaflet/issues/1739) - * Added keyboard accessibility to markers (you can now tab to them and press enter for click behavior). [#1355](https://github.com/Leaflet/Leaflet/issues/1355) - * Improved `TileLayer` zoom animation to eliminate flickering in case one tile layer on top of another or when zooming several times quickly (by [@mourner](https://github.com/mourner) with lots of fixes from [@danzel](https://github.com/danzel)). [#1140](https://github.com/Leaflet/Leaflet/issues/1140) [#1437](https://github.com/Leaflet/Leaflet/issues/1437) [#52](https://github.com/Leaflet/Leaflet/issues/52) - * Subtly improved default popup styles - * Improved attribution control to be much less obtrusive (no "powered by", just a Leaflet link). You can still remove the prefix with `map.attributionControl.setPrefix('')` if you need. - * Improved zoom behavior so that there's no drift of coordinates when you change zoom back and forth without panning. [#426](https://github.com/Leaflet/Leaflet/issues/426) - * Improved double click behavior to zoom while keeping the clicked point fixed (by [@ansis](https://github.com/ansis)). [#1582](https://github.com/Leaflet/Leaflet/issues/1582) - * Improved dragging behavior to not get stuck if mouse moved outside of an iframe containing the map (by [@jfirebaugh](https://github.com/jfirebaugh)). [#1277](https://github.com/Leaflet/Leaflet/issues/1277) [#1782](https://github.com/Leaflet/Leaflet/issues/1782) [#1786](https://github.com/Leaflet/Leaflet/issues/1786) - * Improved box zoom to be cancelable by pressing Escape (by [@yohanboniface](https://github.com/yohanboniface)). [#1438](https://github.com/Leaflet/Leaflet/issues/1438) - * Improved `Marker` popups to close on marker click if opened (by [@popox](https://github.com/popox)). [#1761](https://github.com/Leaflet/Leaflet/issues/1761) - * Significantly improved mass layer removal performance (by [@jfgirard](https://github.com/jfgirard) with fixes from [@danzel](https://github.com/danzel)). [#1141](https://github.com/Leaflet/Leaflet/pull/1141) [#1514](https://github.com/Leaflet/Leaflet/pull/1514) - -#### API improvements - -##### Layers API improvements - - * Added `toGeoJSON` method to various layer types, allowing you to **save your Leaflet layers as GeoJSON**. (by [@jfirebaugh](https://github.com/jfirebaugh)). [#1462](https://github.com/Leaflet/Leaflet/issues/1462) [#712](https://github.com/Leaflet/Leaflet/issues/712) [#1779](https://github.com/Leaflet/Leaflet/issues/1779) - * Added `GeoJSON` `coordsToLatLng` option for dealing with GeoJSON that has non-WGS84 coords (thanks to [@moonlite](https://github.com/moonlite)). [#888](https://github.com/Leaflet/Leaflet/issues/888) [#886](https://github.com/Leaflet/Leaflet/issues/886) - * Improved `Marker` to reuse icon DOM elements when changing icons on the fly (e.g. fixes problems when changing icon on mouse hover) (by [@robpvn](https://github.com/robpvn) & [@danzel](https://github.com/danzel)). [#1726](https://github.com/Leaflet/Leaflet/issues/1726) [#561](https://github.com/Leaflet/Leaflet/issues/561) [#1753](https://github.com/Leaflet/Leaflet/issues/1753) [#1754](https://github.com/Leaflet/Leaflet/pull/1754) - * Added `latlng` property to `Marker` mouse event data. [#1613](https://github.com/Leaflet/Leaflet/issues/1613) - * Added `LayerGroup` `hasLayer` method (by [@rvlasveld](https://github.com/rvlasveld)). [#1282](https://github.com/Leaflet/Leaflet/issues/1282) [#1300](https://github.com/Leaflet/Leaflet/pull/1300) - * Added `LayerGroup` `getLayers` method (by [@tmcw](https://github.com/tmcw)). [#1469](https://github.com/Leaflet/Leaflet/pull/1469) - * Added `LayerGroup` `getLayer` method (by [@gumballhead](https://github.com/gumballhead)). [#1650](https://github.com/Leaflet/Leaflet/pull/1650) - * Improved `LayerGroup` `removeLayer` method to also accept layer `id` (by [@gumballhead](https://github.com/gumballhead)). [#1642](https://github.com/Leaflet/Leaflet/pull/1642) - * Added `Path` `pointerEvents` option for setting pointer-events on SVG-powered vector layers (by [@inpursuit](https://github.com/inpursuit)). [#1053](https://github.com/Leaflet/Leaflet/pull/1053) - * Improved `Polygon` to filter out last point if it's equal to the first one (to fix GeoJSON polygon issues) (by [@snkashis](https://github.com/snkashis)). [#1153](https://github.com/Leaflet/Leaflet/pull/1153) [#1135](https://github.com/Leaflet/Leaflet/issues/1135) - * Improved paths with `clickable: false` to allow mouse events to pass through to objects underneath (by [@snkashis](https://github.com/snkashis)). [#1384](https://github.com/Leaflet/Leaflet/pull/1384) [#1281](https://github.com/Leaflet/Leaflet/issues/1281) - * Improved `L.Util.template` (and correspondingly url-related `TileLayer` options) to support functions for data values (by [@olegsmith](https://github.com/olegsmith)). [#1554](https://github.com/Leaflet/Leaflet/pull/1554) - * Added `TileLayer` `getContainer` method (by [@tmcw](https://github.com/tmcw)). [#1433](https://github.com/Leaflet/Leaflet/pull/1433) - * Fixed `TileLayer.Canvas` `redraw` method chaining (by [@jieter](https://github.com/jieter)). [#1287](https://github.com/Leaflet/Leaflet/pull/1287) - * Added `TileLayer.WMS` `crs` option to be able to use WMS of CRS other than the map CRS (by [@kengu](https://github.com/kengu)). [#942](https://github.com/Leaflet/Leaflet/issues/942) [#945](https://github.com/Leaflet/Leaflet/issues/945) - * Added `popupopen` and `popupclose` events to various layers (by [@Koc](https://github.com/Koc)). [#738](https://github.com/Leaflet/Leaflet/pull/738) - * Added `Popup` `keepInView` option (thanks to [@lapo-luchini](https://github.com/lapo-luchini)) that prevents the popup from going off-screen while it's opened. [#1308](https://github.com/Leaflet/Leaflet/pull/1308) [#1052](https://github.com/Leaflet/Leaflet/issues/1052) - * Added `Marker` `togglePopup` method (by [@popox](https://github.com/popox)). [#1761](https://github.com/Leaflet/Leaflet/issues/1761) - * Added `Popup` `closeOnClick` option that overrides the same `Map` option for specific popups (by [@jfirebaugh](https://github.com/jfirebaugh)). [#1669](https://github.com/Leaflet/Leaflet/issues/1669) - * Improved `Marker` and `Path` `bindPopup` method to also accept `Popup` objects (by [@snkashis](https://github.com/snkashis)). [#1385](https://github.com/Leaflet/Leaflet/pull/1385) [#1208](https://github.com/Leaflet/Leaflet/issues/1208) [#1402](https://github.com/Leaflet/Leaflet/pull/1402) - * Added `Marker` `setPopupContent` method (by [@snkashis](https://github.com/snkashis)). [#1373](https://github.com/Leaflet/Leaflet/pull/1373) - -##### Map API improvements - - * Improved all view changing methods of `Map` (`setView`, `panTo`, `setZoom`, `fitBounds`, etc.) to accept an options object, including the ability to precisely control zoom/pan animations they cause (force disable/enable, etc.). [#1617](https://github.com/Leaflet/Leaflet/pull/1617) [#1616](https://github.com/Leaflet/Leaflet/issues/1616) [#340](https://github.com/Leaflet/Leaflet/issues/340) [#483](https://github.com/Leaflet/Leaflet/issues/483) [#1164](https://github.com/Leaflet/Leaflet/issues/1164) [#1420](https://github.com/Leaflet/Leaflet/issues/1420) - * Improved `Map` `fitBounds` method to accept `padding` (or `paddingTopLeft` and `paddingBottomRight`) options, allowing you to zoom to an area with a certain padding in pixels (usually left for controls). [#859](https://github.com/Leaflet/Leaflet/issues/859) - * Improved `Map` `invalidateSize` to accept options object (`animate` and `pan`, the latter controls if it pans the map on size change). (by [@jacobtoye](https://github.com/jacobtoye) and [@mourner](https://github.com/mourner)). [#1766](https://github.com/Leaflet/Leaflet/issues/1766) [#1767](https://github.com/Leaflet/Leaflet/issues/1767) - * Added `Map` `setZoomAround` method for zooming while keeping a certain point fixed (used by scroll and double-click zooming). [#1157](https://github.com/Leaflet/Leaflet/issues/1157) - * Added `Map` `remove` method to properly destroy the map and clean up all events, and added corresponding `unload` event (by [@jfirebaugh](https://github.com/jfirebaugh) and [@mourner](https://github.com/mourner)). [#1434](https://github.com/Leaflet/Leaflet/issues/1434) [#1101](https://github.com/Leaflet/Leaflet/issues/1101) [#1621](https://github.com/Leaflet/Leaflet/issues/1621) - * Added `Map` `tap` handler that now contains all mobile hacks for enabling quick taps and long holds and `tapTolerance` option specifying the number of pixels you can shift your finger for click to still fire. - * Added `Map` `zoomAnimationThreshold` for setting the max zoom difference with which zoom animation can occur. [#1377](https://github.com/Leaflet/Leaflet/issues/1377) - * Improved `Map` `openPopup` method to also accept `(content, latlng)` signature as a shortcut. - * Improved `Map` `closePopup` method to optionally accept a popup object to close. [#1641](https://github.com/Leaflet/Leaflet/issues/1641) - * Improved `Map` `stopLocate` method to abort resetting map view if calling `locate` with `setView` option. [#747](https://github.com/Leaflet/Leaflet/issues/747) - * Improved `Map` to throw exception if the specified container id is not found (by [@tmcw](htts://github.com/tmcw)). [#1574](https://github.com/Leaflet/Leaflet/pull/1574) - * Improved `Map` `locationfound` event to pass all location data (heading, speed, etc.). [#984](https://github.com/Leaflet/Leaflet/issues/984) [#584](https://github.com/Leaflet/Leaflet/issues/584) [#987](https://github.com/Leaflet/Leaflet/issues/987) [#1028](https://github.com/Leaflet/Leaflet/issues/1028) - * Added `Map` `resize` event. [#1564](https://github.com/Leaflet/Leaflet/issues/1564) - * Added `Map` `zoomlevelschange` event that triggers when the current zoom range (min/max) changes (by [@moonlite](https://github.com/moonlite)). [#1376](https://github.com/Leaflet/Leaflet/pull/1376) - -##### Controls API improvements - - * Added **generic toolbar classes** for reuse by plugin developers (used by zoom control). - * Added `Map` `baselayerchange`, `overlayadd` and `overlayremove` events fired by `Control.Layers` (by [@calvinmetcalf](https://github.com/calvinmetcalf) and [@Xelio](https://github.com/Xelio)). [#1286](https://github.com/Leaflet/Leaflet/issues/1286) [#1634](https://github.com/Leaflet/Leaflet/issues/1634) - * Added `Control` `getContainer` method. [#1409](https://github.com/Leaflet/Leaflet/issues/1409) - -##### Misc API improvements - - * Made Leaflet classes compatible with **CoffeeScript class inheritance** syntax (by [@calvinmetcalf](https://github.com/calvinmetcalf)). [#1345](https://github.com/Leaflet/Leaflet/pull/1345) [#1314](https://github.com/Leaflet/Leaflet/issues/1314) - * Added `cleanAllEventListeners` method (aliased to `off` without arguments) to all events-enabled objects (by [@iirvine](https://github.com/iirvine)). [#1599](https://github.com/Leaflet/Leaflet/issues/1599) - * Added `addOneTimeEventListener` method (aliased to `once`) to all events-enabled objects (by [@iirvine](https://github.com/iirvine)). [#473](https://github.com/Leaflet/Leaflet/issues/473) [#1596](https://github.com/Leaflet/Leaflet/issues/1596) - * Added ability to pass coordinates as simple objects (`{lat: 50, lon: 30}` or `{lat: 50, lng: 30}`). [#1412](https://github.com/Leaflet/Leaflet/issues/1412) - * Added `LatLngBounds` `getNorth`, `getEast`, `getSouth`, `getWest` methods (by [@yohanboniface](https://github.com/yohanboniface)). [#1318](https://github.com/Leaflet/Leaflet/issues/1318) - * Added `AMD` support (Leaflet now registers itself as a `leaflet` AMD module) (with fixes from [@sheppard](https://github.com/sheppard)). [#1364](https://github.com/Leaflet/Leaflet/issues/1364) [#1778](https://github.com/Leaflet/Leaflet/issues/1778) - * Added `L.Util.trim` function (by [@kristerkari](https://github.com/kristerkari)). [#1607](https://github.com/Leaflet/Leaflet/pull/1607) - -#### Development workflow improvements - - * Switched from Jasmine to [Mocha](http://visionmedia.github.io/mocha/) with Expect.js (matchers) and Sinon (spies) for tests (by [@tmcw](https://github.com/tmcw) & [@jfirebaugh](https://github.com/jfirebaugh)). [#1479](https://github.com/Leaflet/Leaflet/issues/1479) - * Added [Karma](http://karma-runner.github.io) integration for running tests in a headless PhantomJS instance and code coverage reporting (by [@edjafarov](https://github.com/edjafarov)). [#1326](https://github.com/Leaflet/Leaflet/issues/1326) [#1340](https://github.com/Leaflet/Leaflet/pull/1340) - * Added [Travis CI integration](https://travis-ci.org/Leaflet/Leaflet) for linting and running tests for each commit and pull request automatically (by [@edjafarov](https://github.com/edjafarov)). [#1336](https://github.com/Leaflet/Leaflet/issues/1336) - * Significantly improved test coverage - * Added compatibility with lazy evaluation scripts (by [@kristerkari](https://github.com/kristerkari)). [#1288](https://github.com/Leaflet/Leaflet/issues/1288) [#1607](https://github.com/Leaflet/Leaflet/issues/1607) [#1288](https://github.com/Leaflet/Leaflet/issues/1288) - -### Bugfixes - -#### General bugfixes - - * Fixed lots of issues with extent restriction by `Map` `maxBounds`. [#1491](https://github.com/Leaflet/Leaflet/issues/1491) [#1475](https://github.com/Leaflet/Leaflet/issues/1475) [#1194](https://github.com/Leaflet/Leaflet/issues/1194) [#900](https://github.com/Leaflet/Leaflet/issues/900) [#1333](https://github.com/Leaflet/Leaflet/issues/1333) - * Fixed occasional crashes by disabling zoom animation if changing zoom level by more than 4 levels. [#1377](https://github.com/Leaflet/Leaflet/issues/1377) - * Fixed a bug with that caused stuttery keyboard panning in some cases (by [@tmcw](https://github.com/tmcw)). [#1710](https://github.com/Leaflet/Leaflet/issues/1710) - * Fixed a bug that caused unwanted scrolling of the page to the top of the map on focus. [#1228](https://github.com/Leaflet/Leaflet/issues/1228) [#1540](https://github.com/Leaflet/Leaflet/issues/1540) - * Fixed a bug where clicking on a marker with an open popup caused the popup to faded in again (by [@snkashis](https://github.com/snkashis)). [#506](https://github.com/Leaflet/Leaflet/issues/560) [#1386](https://github.com/Leaflet/Leaflet/pull/1386) - * Fixed a bug where zoom buttons disabled state didn't update on min/max zoom change (by [@snkashis](https://github.com/snkashis)). [#1372](https://github.com/Leaflet/Leaflet/pull/1372) [#1328](https://github.com/Leaflet/Leaflet/issues/1328) - * Fixed a bug where scrolling slightly wouldn't always zoom out the map (by [@cschwarz](https://github.com/cschwarz)). [#1575](https://github.com/Leaflet/Leaflet/pull/1575) - * Fixed popup close button to not leave an outline after clicking on it and reopening the popup (by [@dotCypress](https://github.com/dotCypress)). [#1537](https://github.com/Leaflet/Leaflet/pull/1537) - * Fixed a bug that prevented tiles from loading during pan animation. - * Fixed a bug with `contextmenu` events on popups falling through to map (by [@snkashis](https://github.com/snkashis)). [#1730](https://github.com/Leaflet/Leaflet/issues/1730) [#1732](https://github.com/Leaflet/Leaflet/issues/1732) - * Fixed `404` tile loading errors when browsing the map off the world bounds. - * Fixed shifted mouse events in some cases with map inside a relatively positioned parent (by [@scooterw](https://github.com/scooterw) and [@jec006](https://github.com/jec006)). [#1670](https://github.com/Leaflet/Leaflet/issues/1670) [#1684](https://github.com/Leaflet/Leaflet/issues/1684) [#1745](https://github.com/Leaflet/Leaflet/issues/1745) [#1744](https://github.com/Leaflet/Leaflet/issues/1744) - * Fixed a bug where tile layer z-index order sometimes broke after view reset. [#1422](https://github.com/Leaflet/Leaflet/issues/1422) - -#### Browser bugfixes - - * Fixed a bug with undesirable page scrolling in Firefox 17+ when you zoom the map by scrolling (by [@jfirebaugh](https://github.com/jfirebaugh)). [#1789](https://github.com/Leaflet/Leaflet/issues/1789) [#1788](https://github.com/Leaflet/Leaflet/issues/1788) - * Fixed a bug where mouse coordinates where shifted in Firefox if the map was inside a positioned block on a scrolled page (by [@joschka](https://github.com/joschka)). [#1365](https://github.com/Leaflet/Leaflet/pull/1365) [#1322](https://github.com/Leaflet/Leaflet/issues/1322) - * Fixed a bug where box zoom didn't work in some cases in Firefox 18+ (by [@fabriceds](https://github.com/fabriceds)). [#1405](https://github.com/Leaflet/Leaflet/pull/1405) - * Fixed a bug where `TileLayer` opacity didn't work in IE 7-8 (by [@javisantana](https://github.com/javisantana) & [@danzel](https://gi -.com/danzel)). [#1084](https://github.com/Leaflet/Leaflet/issues/1084) [#1396](https://github.com/Leaflet/Leaflet/pull/1396) [#1371](https://github.com/Leaflet/Leaflet/issues/1371) - * Fixed Leaflet not working correctly in PhantomJS (by [@rassie](https://github.com/rassie)). [#1501](https://github.com/Leaflet/Leaflet/pull/1501) - -#### Mobile bugfixes - - * Fixed a bug with layers control on WinPhone8/IE10 Touch (by [@danzel](https://github.com/danzel)). [#1635](https://github.com/Leaflet/Leaflet/pull/1635) [#1539](https://github.com/Leaflet/Leaflet/issues/1539) - * Fixed a bug with click sometimes firing twice on WinPhone8/IE10 Touch (by [@danzel](https://github.com/danzel)). [#1694](https://github.com/Leaflet/Leaflet/issues/1694) - * Fixed a bug in Android where click was triggered twice on one tap (by [@jerel](https://github.com/jerel) & [@mourner](https://github.com/mourner)). [#1227](https://github.com/Leaflet/Leaflet/pull/1227) [#1263](https://github.com/Leaflet/Leaflet/issues/1263) [#1785](https://github.com/Leaflet/Leaflet/issues/1785) [#1694](https://github.com/Leaflet/Leaflet/issues/1694) - * Fixed a bug in Android where click on a collapsed layers control would immediately select one of the layers (by [@danzel](https://github.com/danzel)). [#1784](https://github.com/Leaflet/Leaflet/issues/1784) [#1694](https://github.com/Leaflet/Leaflet/issues/1694) - -#### API bugfixes - -##### General API bugfixes - - * Fixed click mouse event inside popups **not propagating outside the map** (fixes issues with jQuery.live and some mobile frameworks that rely on document click listeners). [#301](https://github.com/Leaflet/Leaflet/issues/301) - * Fixed a bug where event listener still fired even if it was removed on the same event in other listener (by [@spamdaemon](https://github.com/spamdaemon)). [#1661](https://github.com/Leaflet/Leaflet/issues/1661) [#1654](https://github.com/Leaflet/Leaflet/issues/1654) - * Fixed a bug where `L.point` and `L.latLng` factories weren't passing `null` and `undefined` values through. - * Fixed `DomEvent` `removeListener` function chaining (by [@pagameba](https://github.com/pagameba)). - * Fixed a bug where `removeEventListener` would throw an error if no events are registered on the object (by [@tjoekbezoer](https://github.com/tjoekbezoer)). [#1632](https://github.com/Leaflet/Leaflet/pull/1632) [#1631](https://github.com/Leaflet/Leaflet/issues/1631) - * Fixed a bug where `Point` `equals` and `contains` methods didn't accept points in array form. - * Fixed a bug where `LatLngBounds` `extend` of an undefined object would cause an error (by [@korzhyk](https://github.com/korzhyk)). [#1688](https://github.com/Leaflet/Leaflet/issues/1688) - * Fixed a bug where `Control.Attribution` `removeAttribution` of inexistant attribution corrupted the attribution text. [#1410](https://github.com/Leaflet/Leaflet/issues/1410) - * Fixed a bug where `setView` on an invisible map caused an error (by [@jfire](https://github.com/jfire)). [#1707](https://github.com/Leaflet/Leaflet/issues/1707) - * Fixed compatibility with Browserify (by [@jfirebaugh](https://github.com/jfirebaugh)). [#1572](https://github.com/Leaflet/Leaflet/pull/1572) - -##### Layers API bugfixes - - * Fixed a bug where default marker icon path wasn't properly detected in some cases in IE6-7 (by [@calvinmetcalf](https://github.com/calvinmetcalf)). [#1294](https://github.com/Leaflet/Leaflet/pull/1294) - * Fixed a bug where `TileLayer.WMS` param values weren't escaped in URLs (by [@yohanboniface](https://github.com/yohanboniface)). [#1317](https://github.com/Leaflet/Leaflet/issues/1317) - * Fixed a bug where layers that belong to multiple feature groups didn't propagate events correctly (by [@danzel](https://github.com/danzel)). [#1359](https://github.com/Leaflet/Leaflet/pull/1359) - * Fixed a bug where `TileLayer.WMS` `tileSize` option was ignored (by [@brianhatchl](https://github.com/brianhatchl)). [#1080](https://github.com/brianhatchl) - * Fixed a bug where `Polyline` constructor could overwrite the source array (by [@snkashis](https://github.com/snkashis) and [@danzel](https://github.com/danzel)). [#1439](https://github.com/Leaflet/Leaflet/pull/1439) [#1092](https://github.com/Leaflet/Leaflet/issues/1092) [#1246](https://github.com/Leaflet/Leaflet/issues/1246) [#1426](https://github.com/Leaflet/Leaflet/issues/1426) - * Fixed a bug where marker dragging disabling/enabling wouldn't always work correctly (by [@snkashis](https://github.com/snkashis) and [@escaped](https://github.com/escaped)). [#1471](https://github.com/Leaflet/Leaflet/pull/1471) [#1551](https://github.com/Leaflet/Leaflet/pull/1551) - * Fixed `TileLayer` to prevent incorrect subdomain in case of negative tile coordinates (by [@malexeev](https://github.com/malexeev)). [#1532](https://github.com/Leaflet/Leaflet/pull/1532) - * Fixed polygons to normalize holes (remove last point if it's equal to the first one) (by [@jfirebaugh](https://github.com/jfirebaugh)). [#](https://github.com/Leaflet/Leaflet/pull/1467) [#1459](https://github.com/Leaflet/Leaflet/issues/1459) - * Fixed `DivIcon` `html` option to accept `0` as a value (by [@stuporglue](https://github.com/stuporglue)). [#1633](https://github.com/Leaflet/Leaflet/pull/1633) - * Fixed a bug with Canvas-based paths throwing an error on `mousemove` in certain conditions. [#1615](https://github.com/Leaflet/Leaflet/issues/1615) - * Fixed a bug where copies of the world wouldn't load if you set `TileLayer` `bounds` (by [@ansis](https://github.com/ansis)). [#1618](https://github.com/Leaflet/Leaflet/issues/1618) - * Fixed a bug where `TileLayer` `load` event wouldn't always fire correctly. [#1565](https://github.com/Leaflet/Leaflet/issues/1565) - * Fixed `TileLayer.WMS` compatibility with some old servers that only accepted request parameters in uppercase. [#1751](https://github.com/Leaflet/Leaflet/issues/1751) - * Fixed a bug with incorrect `L.Icon.Default.imagePath` detection in some cases. [#1657](https://github.com/Leaflet/Leaflet/issues/1657) - * Fixed a bug where layer `onRemove` was still called even if it was never added (by [@jfirebaugh](https://github.com/jfirebaugh)). [#1729](https://github.com/Leaflet/Leaflet/issues/1729) - * Fixed a bug where calling `setRadius` on a Canvas-powered `CircleMarker` would cause an infinite loop (by [@snkashis](https://github.com/snkashis)). [#1712](https://github.com/Leaflet/Leaflet/issues/1712) [#1713](https://github.com/Leaflet/Leaflet/issues/1713) [#1728](https://github.com/Leaflet/Leaflet/issues/1728) - * Renamed `marker-icon@2x.png` to `marker-icon-2x.png` to fix compatibility with Google AppEngine. [#1552](https://github.com/Leaflet/Leaflet/issues/1552) [#1553](https://github.com/Leaflet/Leaflet/issues/1553) - * Fixed a bug where `popupclose` and `popupopen` events weren't fired for multipolygons and multipolylines (by [@tmcw](https://github.com/tmcw)). [#1681](https://github.com/Leaflet/Leaflet/issues/1681) - -##### Map API bugfixes - - * Fixed a bug where `Map` `fitBounds` wouldn't work correctly with large bounds (thanks to [@MaZderMind](https://github.com/MaZderMind)). [#1069](https://github.com/Leaflet/Leaflet/issues/1069) - * Fixed a bug where `Map` `hasLayer` wasn't handling `null` objects (by [@rvlasveld](https://github.com/rvlasveld)). [#1282](https://github.com/Leaflet/Leaflet/issues/1282) [#1302](https://github.com/Leaflet/Leaflet/pull/1302) - * Fixed a bug where `Map` `moveend` fired before `dragend` on drag (by [@oslek](https://github.com/oslek)). [#1374](https://github.com/Leaflet/Leaflet/pull/1374) - * Fixed a bug where panning with inertia produced an excessive `Map` `movestart` event on inertia start (by [@oslek](https://github.com/oslek)). [#1374](https://github.com/Leaflet/Leaflet/pull/1374) - * Fixed a bug where `Map` `moveend` fired repeatedly on window resize even if the actual map size didn't change (by [@oslek](https://github.com/oslek)). [#1374](https://github.com/Leaflet/Leaflet/pull/1374) - * Fixed a bug where `Map` `moveend` sometimes wasn't fired after drag (particularly often when dragging with a trackpad). - * Fixed a bug that would cause an error when trying to get the state of the map in a `Map` `load` event listener. [#962](https://github.com/Leaflet/Leaflet/issues/962) - * Added `Map` `autopanstart` event back (it was removed occasionally in previous version). [#1375](https://github.com/Leaflet/Leaflet/issues/1375) - * Fixed a bug with removing previously set `Map` `maxBounds` (by [@jec006](https://github.com/jec006)). [#1749](https://github.com/Leaflet/Leaflet/issues/1749) [#1750](https://github.com/Leaflet/Leaflet/issues/1750) - - -## 0.5.1 (February 6, 2013) - - * Fixed a regression with `GeoJSON` not accepting arrays of `FeatureCollection` (by [@snkashis](https://github.com/snkashis)). [#1299](https://github.com/Leaflet/Leaflet/pull/1299) [#1298](https://github.com/Leaflet/Leaflet/issues/1298) - * Fixed a regression with `CirleMarker` `setRadius` not working if called before adding the layer to the map (by [@danzel](https://github.com/danzel)). [#1342](https://github.com/Leaflet/Leaflet/issues/1342) [#1297](https://github.com/Leaflet/Leaflet/issues/1297) - -## 0.5 (January 17, 2013) - -### Breaking changes - -Be sure to read through these changes to avoid any issues when upgrading from older versions: - - * Removed default `LatLng` wrapping/clamping of coordinates (`-180, -90` to `180, 90`), wrapping moved to an explicit method (`LatLng` `wrap`). - * Disabled `Map` `worldCopyJump` option by default (jumping back to the original world copy when panning out of it). Enable it explicitly if you need it. - * Changed styles for the zoom control (you may need to update your custom styles for it). - -### Improvements - -#### Usability improvements - -##### Interaction - - * Added touch zoom, pan and double tap support for **IE10 touch devices and Metro apps** (by [@danzel](https://github.com/danzel) and [@veproza](https://github.com/veproza) with help from [@oliverheilig](https://github.com/oliverheilig)). [#1076](https://github.com/Leaflet/Leaflet/pull/1076) [#871](https://github.com/Leaflet/Leaflet/issues/871) - * **Improved panning inertia** to be much more natural and smooth. - * **Improved dragging cursors** in Chrome, Safari and Firefox (now grabbing hand cursors are used). - * Improved zoom animation curve for a better feel overall. - * Improved scroll wheel zoom to be more responsive. - * Improved panning animation performance in IE6-8. - -##### Controls - - * **Improved zoom control design** to look better, more neutral and in line with other controls, making it easier to customize and fit different website designs. Replaced +/- images with text. - * Improved zoom control to zoom by 3 levels if you hold shift while clicking on a button. - * Improved zoom control buttons to become visually disabled when min/max zoom is reached. [#917](https://github.com/Leaflet/Leaflet/issues/917) - * Improved scale control styles. - * Improved fallback control styles for IE6-8. - -##### Other - - * Added **retina support for markers** (through `Icon` `iconRetinaUrl` and `shadowRetinaUrl` options) (by [@danzel](https://github.com/danzel)). [#1048](https://github.com/Leaflet/Leaflet/issues/1048) [#1174](https://github.com/Leaflet/Leaflet/pull/1174) - * Added retina-sized default marker icon in addition to standard one (along with its SVG source and with some subtle design improvements) (by [@danzel](https://github.com/danzel)). [#1048](https://github.com/Leaflet/Leaflet/issues/1048) [#1174](https://github.com/Leaflet/Leaflet/pull/1174) - * Improved vectors updating/removing performance on Canvas backend (by [@danzel](https://github.com/danzel)). [#961](https://github.com/Leaflet/Leaflet/pull/961) - * Cut total images size from 10KB to 3.2KB with [Yahoo Smush.it](http://www.smushit.com/ysmush.it/). Thanks to Peter Rounce for suggestion. - -#### API improvements - - * Replaced `L.Transition` with a much better and simpler `L.PosAnimation`. - * Added `Class` `addInitHook` method for **adding constructor hooks to any classes** (great extension point for plugin authors). [#1123](https://github.com/Leaflet/Leaflet/issues/1123) - * Added `Map` `whenReady` method (by [@jfirebaugh](https://github.com/jfirebaugh)). [#1063](https://github.com/Leaflet/Leaflet/pull/1063) - * Added optional `delta` argument to `Map` `zoomIn` and `zoomOut` (1 by default). - * Added `isValid` method to `LatLngBounds` and `Bounds` (by [@domoritz](https://github.com/domoritz)). [#972](https://github.com/Leaflet/Leaflet/pull/972) - * Added `Point` `equals` method. - * Added `Bounds` `getSize` method. - * Improved markers and vectors click event so that it propagates to map if no one is listening to it (by [@danzel](https://github.com/danzel)). [#834](https://github.com/Leaflet/Leaflet/issues/834) [#1033](https://github.com/Leaflet/Leaflet/pull/1033) - * Added `Path` `unbindPopup` and `closePopup` methods. - * Added `Path` `add` and `remove` event. - * Added `Marker` `riseOnHover` and `riseOffset` options (for bringing markers to front on hover, disabled by default) (by [jacobtoye](https://github.com/jacobtoye)). [#914](https://github.com/Leaflet/Leaflet/pull/914) [#920](https://github.com/Leaflet/Leaflet/issues/920) - * Added `Marker` `move` and `remove` events. - * Added `Marker` `contextmenu` event. [#223](https://github.com/Leaflet/Leaflet/issues/223) - * Added `Popup` `zoomAnimation` option (useful to disable when displaying flash content inside popups [#999](https://github.com/Leaflet/Leaflet/issues/999)). - * Added `FeatureGroup` `layeradd` and `layerremove` events (by [@jacobtoye](https://github.com/jacobtoye)). [#1122](https://github.com/Leaflet/Leaflet/issues/1122) - * Added `Control.Layers` `baselayerchange` event (by [@jfirebaugh](https://github.com/jfirebaugh)). [#1064](https://github.com/Leaflet/Leaflet/pull/1064) - * Improved `Control.Layers` to support HTML in layer names (by [@aparshin](https://github.com/aparshin)). [#1055](https://github.com/Leaflet/Leaflet/pull/1055) [#1099](https://github.com/Leaflet/Leaflet/issues/1099) - * Added `CRS.Simple` to the list of built-in CRS and improved it to be more usable out of the box (it has different default scaling and transformation now), see `debug/map/simple-proj.html` for an example. - * Removed `Browser` `ua`, `gecko`, `opera` properties (no longer needed). - * Added `L.extend`, `L.bind`, `L.stamp`, `L.setOptions` shortcuts for corresponding `L.Util` methods. - * Disabled clearing of map container contents on map initialization (as a result of fixing [#278](https://github.com/Leaflet/Leaflet/issues/278)). - * Added `L.Util.isArray` function (by [@oslek](https://github.com/oslek)). [#1279](https://github.com/Leaflet/Leaflet/pull/1279) - * Added `mouseover` and `mouseout` events to canvas-based vector layers (by [@snkashis](https://github.com/snkashis)). [#1403](https://github.com/Leaflet/Leaflet/pull/1403) - * Added `Map` `eachLayer` to iterate over all layers added to the map (by [@jfirebaugh](https://github.com/jfirebaugh)). [#1457](https://github.com/Leaflet/Leaflet/pull/1457) - * Added `TileLayer` `bounds` option to limit tile loading to a specific region (by [@adimitrov](https://github.com/adimitrov)). [#991](https://github.com/Leaflet/Leaflet/pull/991) - -### Bugfixes - -#### General bugfixes - - * Fixed broken tiles and zooming in RTL layouts (by [@danzel](https://github.com/danzel)). [#1099](https://github.com/Leaflet/Leaflet/pull/1099) [#1095](https://github.com/Leaflet/Leaflet/issues/1095) - * Fixed a bug with pan animation where it jumped to its end position if you tried to drag the map. - * Fixed a bug where shift-clicking on a map would zoom it to the max zoom level. - * Fixed a glitch with zooming in while panning animation is running. - * Fixed a glitch with dragging the map while zoom animation is running. - * Fixed a bug where slight touchpad scrolling or one-wheel scrolling wouln't always perform zooming. [#1039](https://github.com/Leaflet/Leaflet/issues/1039) - * Fixed a bug where `panBy` wouldn't round the offset values (so it was possible to make the map blurry with it). [#1085](https://github.com/Leaflet/Leaflet/issues/1085) - * Fixed a bug where you couldn't scroll the layers control with a mouse wheel. - * Fixed a regression where WMS tiles wouldn't wrap on date lines. [#970](https://github.com/Leaflet/Leaflet/issues/970) - * Fixed a bug where mouse interaction was affected by map container border width (by [@mohlendo](https://github.com/mohlendo)). [#1204](https://github.com/Leaflet/Leaflet/issues/1205) [#1205](https://github.com/Leaflet/Leaflet/pull/1205) - * Fixed a bug with weird vector zoom animation when using Canvas for rendering (by [@danzel](https://github.com/danzel)). [#1187](https://github.com/Leaflet/Leaflet/issues/1187) [#1188](https://github.com/Leaflet/Leaflet/pull/1188) - * Fixed a bug where max bounds limitation didn't work when navigating the map with a keyboard (by [@snkashis](https://github.com/snkashis)). [#989](https://github.com/Leaflet/Leaflet/issues/989) [#1221](https://github.com/Leaflet/Leaflet/pull/1221) - -#### API bugfixes - - * Fixed a bug where `TileLayer` `bringToBack` didn't work properly in some cases (by [@danzel](https://github.com/danzel)). [#963](https://github.com/Leaflet/Leaflet/pull/963) [#959](https://github.com/Leaflet/Leaflet/issues/959) - * Fixed a bug where removing a tile layer while dragging would throw an error (by [@danzel](https://github.com/danzel)). [#965](https://github.com/Leaflet/Leaflet/issues/965) [#968](https://github.com/Leaflet/Leaflet/pull/968) - * Fixed a bug where middle marker wasn't removed after deleting 2 end nodes from a polyline (by [@Svad](https://github.com/Svad)). [#1022](https://github.com/Leaflet/Leaflet/issues/1022) [#1023](https://github.com/Leaflet/Leaflet/pull/1023) - * Fixed a bug where `Map` `load` event happened too late (after `moveend`, etc.) (by [@jfirebaugh](https://github.com/jfirebaugh)). [#1027](https://github.com/Leaflet/Leaflet/pull/1027) - * Fixed `Circle` `getBounds` to return correct bounds and work without adding the circle to a map. [#1068](https://github.com/Leaflet/Leaflet/issues/1068) - * Fixed a bug where removing `Popup` on `viewreset` throwed an error (by [fnicollet](https://github.com/fnicollet) and [@danzel](https://github.com/danzel)). [#1098](https://github.com/Leaflet/Leaflet/pull/1098) [#1094](https://github.com/Leaflet/Leaflet/issues/1094) - * Fixed a bug where `TileLayer.Canvas` `drawTile` didn't receive tile zoom level in arguments. - * Fixed a bug where `GeoJSON` `resetStyle` would not fully reset a layer to its default style. [#1112](https://github.com/Leaflet/Leaflet/issues/1112) - * Fixed a bug that caused infinite recursion when using `latLngBounds` factory with coordinates as string values. [#933](https://github.com/Leaflet/Leaflet/issues/933) - * Fixed chaining on `Marker` `setIcon`, `setZIndexOffset`, `update` methods. [#1176](https://github.com/Leaflet/Leaflet/issues/1176) - * Fixed a bug with mouse interaction when the map container contained children with position other than absolute. [#278](https://github.com/Leaflet/Leaflet/issues/278) - * Fixed a bug with fill/stroke opacity conflicts when using Canvas for rendering (by [@danzel](https://github.com/danzel)). [#1186](https://github.com/Leaflet/Leaflet/issues/1186) [#1889](https://github.com/Leaflet/Leaflet/pull/1189) - * Fixed a bug where `FeatureGroup` `bindPopup` didn't take options into account. - * Fixed a bug where Canvas-based vector layers didn't cleanup click event on removal properly (by [@snkashis](https://github.com/snkashis)). [#1006](https://github.com/Leaflet/Leaflet/issues/1006) [#1273](https://github.com/Leaflet/Leaflet/pull/1273) - * Fixed a bug where `CircleMarker` `setStyle` didn't take `radius` into account (by [@fdlk](https://github.com/fdlk)). [#1012](https://github.com/Leaflet/Leaflet/issues/1012) [#1013](https://github.com/Leaflet/Leaflet/pull/1013) - * Fixed a bug where null GeoJSON geometries would throw an error instead of skipping (by [@brianherbert](https://github.com/brianherbert)). [#1240](https://github.com/Leaflet/Leaflet/pull/1240) - * Fixed a bug where Canvas-based vector layers passed incorrect `layer` event property on click (by [@snkashis](https://github.com/snkashis)). [#1215](https://github.com/Leaflet/Leaflet/issues/1215) [#1243](https://github.com/Leaflet/Leaflet/pull/1243) - * Fixed a bug where `TileLayer.WMS` didn't work correctly if the base URL contained query parameters (by [@snkashis](https://github.com/snkashis)). [#973](https://github.com/Leaflet/Leaflet/issues/973) [#1231](https://github.com/Leaflet/Leaflet/pull/1231) - * Fixed a bug where removing a polyline in editing state wouldn't clean up the editing handles (by [@mehmeta](https://github.com/mehmeta)). [#1233](https://github.com/Leaflet/Leaflet/pull/1233) - * Fixed a bug where removing a vector layer with a bound popup wouldn't clean up its click event properly (by [@yohanboniface](https://github.com/yohanboniface)). [#1229](https://github.com/Leaflet/Leaflet/pull/1229) - * Fixed a bug where `GeoJSON` features with `GeometryCollection` didn't pass properties to `pointToLayer` function (by [@calvinmetcalf](https://github.com/calvinmetcalf)). [#1097](https://github.com/Leaflet/Leaflet/pull/1097) - * Fixed `FeatureGroup` `eachLayer` chaining. [#1452](https://github.com/Leaflet/Leaflet/issues/1452) - -#### Browser bugfixes - - * Fixed a bug with map **freezing after zoom on Android 4.1**. [#1182](https://github.com/Leaflet/Leaflet/issues/1182) - * Fixed a bug where "Not implemented" error sometimes appeared in IE6-8 (by [@bryguy](https://github.com/bryguy) and [@lookfirst](https://github.com/lookfirst)). [#892](https://github.com/Leaflet/Leaflet/issues/892) [#893](https://github.com/Leaflet/Leaflet/pull/893) - * Fixed compatibility with SmoothWheel extension for Firefox (by [@waldir](https://github.com/waldir)). [#1011](https://github.com/Leaflet/Leaflet/pull/1011) - * Fixed a bug with popup layout in IE6-7 (by [@danzel](https://github.com/danzel)). [#1117](https://github.com/Leaflet/Leaflet/issues/1117) - * Fixed a bug with incorrect box zoom opacity in IE6-7 (by [@jacobtoye](https://github.com/jacobtoye)). [#1072](https://githubcom/Leaflet/Leaflet/pull/1072) - * Fixed a bug with box zoom throwing a JS error in IE6-7 (by [@danzel](https://github.com/danzel)). [#1071](https://github.com/Leaflet/Leaflet/pull/1071) - * Fixed a bug where `TileLayer` `bringToFront/Back()` throwed an error in IE6-8. [#1168](https://github.com/Leaflet/Leaflet/issues/1168) - * Fixed array type checking in the code to be more consistent in a cross-frame environment (by [@oslek](https://github.com/oslek)). [#1279](https://github.com/Leaflet/Leaflet/pull/1279) - * Fixed a bug with `-` key not working in Firefox 15+ (thanks to [@mattesCZ](https://github.com/mattesCZ)). [#869](https://github.com/Leaflet/Leaflet/issues/869) - -## 0.4.5 (October 25, 2012) - - * Fixed a bug with **wonky zoom animation in IE10** (by [@danzel](https://github.com/danzel)). [#1007](https://github.com/Leaflet/Leaflet/pull/1007) - * Fixed a bug with **wonky zoom animation in Chrome 23+** (by [@danzel](https://github.com/danzel)). [#1060](https://github.com/Leaflet/Leaflet/pull/1060) [#1056](https://github.com/Leaflet/Leaflet/issues/1056) - -## 0.4.4 (August 7, 2012) - -### Improvements - - * Improved `GeoJSON` `setStyle` to also accept function (like the corresponding option). - * Added `GeoJSON` `resetStyle(layer)`, useful for resetting hover state. - * Added `feature` property to layers created with `GeoJSON` (containing the GeoJSON feature data). - * Added `FeatureGroup` `bringToFront` and `bringToBack` methods (so that they would work for multipolys). - * Added optional `animate` argument to `Map` `invalidateSize` (by [@ajbeaven](https://github.com/ajbeaven)). [#857](https://github.com/Leaflet/Leaflet/pull/857) - -### Bugfixes - - * Fixed a bug where tiles sometimes disappeared on initial map load on Android 2/3 (by [@danzel](https://github.com/danzel)). [#868](https://github.com/Leaflet/Leaflet/pull/868) - * Fixed a bug where map would occasionally flicker near the border on zoom or pan on Chrome. - * Fixed a bug where `Path` `bringToFront` and `bringToBack` didn't return `this`. - * Removed zoom out on Win/Meta key binding (since it interferes with global keyboard shortcuts). [#869](https://github.com/Leaflet/Leaflet/issues/869) - -## 0.4.2 (August 1, 2012) - - * Fixed a bug where layers control radio buttons would not work correctly in IE7 (by [@danzel](https://github.com/danzel)). [#862](https://github.com/Leaflet/Leaflet/pull/862) - * Fixed a bug where `FeatureGroup` `removeLayer` would unbind popups of removed layers even if the popups were not put by the group (affected [Leaflet.markercluster](https://github.com/danzel/Leaflet.markercluster) plugin) (by [@danzel](https://github.com/danzel)). [#861](https://github.com/Leaflet/Leaflet/pull/861) - -## 0.4.1 (July 31, 2012) - - * Fixed a bug that caused marker shadows appear as opaque black in IE6-8. [#850](https://github.com/Leaflet/Leaflet/issues/850) - * Fixed a bug with incorrect calculation of scale by the scale control. [#852](https://github.com/Leaflet/Leaflet/issues/852) - * Fixed broken L.tileLayer.wms class factory (by [@mattcurrie](https://github.com/mattcurrie)). [#856](https://github.com/Leaflet/Leaflet/issues/856) - * Improved retina detection for `TileLayer` `detectRetina` option (by [@sxua](https://github.com/sxua)). [#854](https://github.com/Leaflet/Leaflet/issues/854) - -## 0.4 (July 30, 2012) - -### API simplification - -Leaflet 0.4 contains several API improvements that allow simpler, jQuery-like syntax ([example](https://gist.github.com/3038879)) while being backwards compatible with the previous approach (so you can use both styles): - - * Improved most methods and options to accept `LatLng`, `LatLngBounds`, `Point` and `Bounds` values in an array form (e.g. `map.panTo([lat, lng])` will be the same as `map.panTo(new L.LatLng(lat, lng))`) - * Added `addTo` method to all layer classes, e.g. `marker.addTo(map)` is equivalent to `map.addLayer(marker)` - * Added factory methods to most classes to be able to write code without `new` keyword, named the same as classes but starting with a lowercase letter, e.g. `L.map('map')` is the same as `new L.Map('map')` - -### Notable new features - - * Added configurable **panning inertia** - after a quick pan, the map slows down in the same direction. - * Added **keyboard navigation** for panning/zooming with keyboard arrows and +/- keys (by [@ericmmartinez](https://github.com/ericmmartinez)). [#663](https://github.com/Leaflet/Leaflet/pull/663) [#646](https://github.com/Leaflet/Leaflet/issues/646) - * Added smooth **zoom animation of markers, vector layers, image overlays and popups** (by [@danzel](https://github.com/danzel)). [#740](https://github.com/Leaflet/Leaflet/pull/740) [#758](https://github.com/Leaflet/Leaflet/issues/758) - * Added **Android 4+ pinch-zoom** support (by [@danzel](https://github.com/danzel)). [#774](https://github.com/Leaflet/Leaflet/pull/774) - * Added **polyline and polygon editing**. [#174](https://github.com/Leaflet/Leaflet/issues/174) - * Added an unobtrusive **scale control**. - * Added **DivIcon** class that easily allows you to create lightweight div-based markers. - * Added **Rectangle** vector layer (by [@JasonSanford](https://github.com/JasonSanford)). [#504](https://github.com/Leaflet/Leaflet/pull/504) - -### Improvements - -#### Usability improvements - - * Improved zooming so that you don't get a blank map when you zoom in or out twice quickly (by [@danzel](https://github.com/danzel)). [#7](https://github.com/Leaflet/Leaflet/issues/7) [#729](https://github.com/Leaflet/Leaflet/pull/729) - * Drag-panning now works even when there are markers in the starting point (helps on maps with lots of markers). [#506](https://github.com/Leaflet/Leaflet/issues/506) - * Improved panning performance even more (there are no wasted frames now). - * Improved pinch-zoom performance in mobile Chrome and Firefox. - * Improved map performance on window resize. - * Replaced box-shadow with border on controls for mobile devices to improve performance. - * Slightly improved default popup styling. - * Added `TileLayer` `detectRetina` option (`false` by default) that makes tiles show in a higher resolution on iOS retina displays (by [@Mithgol](https://github.com/Mithgol)). [#586](https://github.com/Leaflet/Leaflet/pull/586) - -#### GeoJSON API changes - -GeoJSON API was improved to be simpler and more flexible ([example](https://gist.github.com/3062900)). The changes are not backwards-compatible, so be sure to update your old code. - - * Added `style` option for styling vector layers, passed either as an object or as a function (to style vector layers according to GeoJSON properties). - * Added `filter` option to leave out features that don't correspond to a certain criteria (e.g. based on properties). - * Added `onEachFeature` option to execute certain code on each feature layer based on its properties (binding popups, etc). - * Changed `pointToLayer` function signature to provide `geojson` in addition to `latlng` when creating point features for more flexibility. - -#### Icon API changes - -Icon API was improved to be more flexible, but one of the changes is backwards-incompatible: you now need to pass different icon properties (like `iconUrl`) inside an options object ([example](https://gist.github.com/3076084)). - - * Converted `Icon` properties to options, changed constructor signature to `Icon(options)`. - * Moved default marker icon options to `L.Icon.Default` class (which extends from `L.Icon`). - * Added `Icon` `className` option to assign a custom class to an icon. - * Added `Icon` `shadowAnchor` option to set the anchor of the shadow. - * Made all `Icon` options except `iconUrl` optional (if not specified, they'll be chosen automatically or implemented using CSS). Anchor is centered by default (if size is specified), and otherwise can be set through CSS using negative margins. - -#### Control API changes - - * Added `setPosition` and `getPosition` to all controls, as well as ability to pass certain position as an option when creating a control. - * Made controls implementation easier (now more magic happens under the hood). - * Replaced ugly control position constants (e.g. `L.Control.Position.TOP_LEFT`) with light strings (`'topleft'`, `'bottomright'`, etc.) - -#### Other breaking API changes - - * Improved `TileLayer` constructor to interpolate URL template values from options (removed third `urlParams` argument). - * Changed `TileLayer` `scheme: 'tms'` option to `tms: true`. - * Removed `Map` `locateAndSetView` method (use `locate` with `setView: true` option) - * Changed popup `minWidth` and `maxWidth` options to be applied to content element, not the whole popup. - * Moved `prefix` argument to `options` in `Control.Attribution` constructor. - * Renamed `L.VERSION` to `L.version`. - -#### Other API improvements - - * Improved `on` and `off` methods to also accept `(eventHash[, context])`, as well as multiple space-separated events (by [@Guiswa](https://github.com/Guiswa)). [#770](https://github.com/Leaflet/Leaflet/pull/770) - * Improved `off` to remove all listeners of the event if no function was specified (by [@Guiswa](https://github.com/Guiswa)). [#770](https://github.com/Leaflet/Leaflet/pull/770) [#691](https://github.com/Leaflet/Leaflet/issues/691) - * Added `TileLayer` `setZIndex` method for controlling the order of tile layers (thanks to [@mattcurrie](https://github.com/mattcurrie)). [#837](https://github.com/Leaflet/Leaflet/pull/837) - * Added `Control.Layers` `autoZIndex` option (on by default) to preserve the order of tile layers when switching. - * Added `TileLayer` `redraw` method for re-requesting tiles (by [@greeninfo](https://github.com/greeninfo)). [#719](https://github.com/Leaflet/Leaflet/issues/719) - * Added `TileLayer` `setUrl` method for dynamically changing the tile URL template. - * Added `bringToFront` and `bringToBack` methods to `TileLayer`, `ImageOverlay` and vector layers. [#185](https://github.com/Leaflet/Leaflet/issues/185) [#505](https://github.com/Leaflet/Leaflet/issues/505) - * Added `TileLayer` `loading` event that fires when its tiles start to load (thanks to [@lapinos03](https://github.com/lapinos03)). [#177](https://github.com/Leaflet/Leaflet/issues/177) - * Added `TileLayer.WMS` `setParams` method for setting WMS parameters at runtime (by [@greeninfo](https://github.com/greeninfo)). [#719](https://github.com/Leaflet/Leaflet/issues/719) - * Added `TileLayer.WMS` subdomain support (`{s}` in the url) (by [@greeninfo](https://github.com/greeninfo)). [#735](https://github.com/Leaflet/Leaflet/issues/735) - * Added `originalEvent` property to `MouseEvent` (by [@k4](https://github.com/k4)). [#521](https://github.com/Leaflet/Leaflet/pull/521) - * Added `containerPoint` property to `MouseEvent`. [#413](https://github.com/Leaflet/Leaflet/issues/413) - * Added `contextmenu` event to vector layers (by [@ErrorProne](https://github.com/ErrorProne)). [#500](https://github.com/Leaflet/Leaflet/pull/500) - * Added `LayerGroup` `eachLayer` method for iterating over its members. - * Added `FeatureGroup` `mousemove` and `contextmenu` events (by [@jacobtoye](https://github.com/jacobtoye)). [#816](https://github.com/Leaflet/Leaflet/pull/816) - * Added chaining to `DomEvent` methods. - * Added `on` and `off` aliases for `DomEvent` `addListener` and `removeListener` methods. - * Added `L_NO_TOUCH` global variable switch (set it before Leaflet inclusion) which disables touch detection, helpful for desktop apps built using QT. [#572](https://github.com/Leaflet/Leaflet/issues/572) - * Added `dashArray` option to vector layers for making dashed strokes (by [jacobtoye](https://github.com/jacobtoye)). [#821](https://github.com/Leaflet/Leaflet/pull/821) [#165](https://github.com/Leaflet/Leaflet/issues/165) - * Added `Circle` `getBounds` method. [#440](https://github.com/Leaflet/Leaflet/issues/440) - * Added `Circle` `getLatLng` and `getRadius` methods (by [@Guiswa](https://github.com/Guiswa)). [#655](https://github.com/Leaflet/Leaflet/pull/655) - * Added `openPopup` method to all vector layers. [#246](https://github.com/Leaflet/Leaflet/issues/246) - * Added public `redraw` method to vector layers (useful if you manipulate their `LatLng` points directly). - * Added `Marker` `opacity` option and `setOpacity` method. - * Added `Marker` `update` method. [#392](https://github.com/Leaflet/Leaflet/issues/392) - * Improved `Marker` `openPopup` not to raise an error if it doesn't have a popup. [#507](https://github.com/Leaflet/Leaflet/issues/507) - * Added `ImageOverlay` `opacity` option and `setOpacity` method. [#438](https://github.com/Leaflet/Leaflet/issues/438) - * Added `Popup` `maxHeight` option that makes content inside the popup scrolled if it doesn't fit the specified max height. - * Added `Popup` `openOn(map)` method (similar to `Map` `openPopup`). - * Added `Map` `getContainer` method (by [@Guiswa](https://github.com/Guiswa)). [#654](https://github.com/Leaflet/Leaflet/pull/654) - * Added `Map` `containerPointToLatLng` and `latLngToContainerPoint` methods. [#474](https://github.com/Leaflet/Leaflet/issues/474) - * Added `Map` `addHandler` method. - * Added `Map` `mouseup` and `autopanstart` events. - * Added `LatLngBounds` `pad` method that returns bounds extended by a percentage (by [@jacobtoye](https://github.com/jacobtoye)). [#492](https://github.com/Leaflet/Leaflet/pull/492) - * Moved dragging cursor styles from JS code to CSS. - -### Bug fixes - -#### General bugfixes - - * Fixed a bug where the map was zooming incorrectly inside a `position: fixed` container (by [@chx007](https://github.com/chx007)). [#602](https://github.com/Leaflet/Leaflet/pull/602) - * Fixed a bug where scaled tiles weren't cleared up after zoom in some cases (by [@cfis](https://github.com/cfis)) [#683](https://github.com/Leaflet/Leaflet/pull/683) - * Fixed a bug where map wouldn't drag over a polygon with a `mousedown` listener. [#834](https://github.com/Leaflet/Leaflet/issues/834) - -#### API bugfixes - - * Fixed a regression where removeLayer would not remove corresponding attribution. [#488](https://github.com/Leaflet/Leaflet/issues/488) - * Fixed a bug where popup close button wouldn't work on manually added popups. [#423](https://github.com/Leaflet/Leaflet/issues/423) - * Fixed a bug where marker click event would stop working if you dragged it and then disabled dragging. [#434](https://github.com/Leaflet/Leaflet/issues/434) - * Fixed a bug where `TileLayer` `setOpacity` wouldn't work when setting it back to 1. - * Fixed a bug where vector layer `setStyle({stroke: false})` wouldn't remove stroke and the same for fill. [#441](https://github.com/Leaflet/Leaflet/issues/441) - * Fixed a bug where `Marker` `bindPopup` method wouldn't take `offset` option into account. - * Fixed a bug where `TileLayer` `load` event wasn't fired if some tile didn't load (by [@lapinos03](https://github.com/lapinos03) and [@cfis](https://github.com/cfis)) [#682](https://github.com/Leaflet/Leaflet/pull/682) - * Fixed error when removing `GeoJSON` layer. [#685](https://github.com/Leaflet/Leaflet/issues/685) - * Fixed error when calling `GeoJSON` `clearLayer` (by [@runderwood](https://github.com/runderwood)). [#617](https://github.com/Leaflet/Leaflet/pull/617) - * Fixed a bug where `Control` `setPosition` wasn't always working correctly (by [@ericmmartinez](https://github.com/ericmmartinez)). [#657](https://github.com/Leaflet/Leaflet/pull/657) - * Fixed a bug with `Util.bind` sometimes losing arguments (by [@johtso](https://github.com/johtso)). [#588](https://github.com/Leaflet/Leaflet/pull/588) - * Fixed a bug where `drag` event was sometimes fired after `dragend`. [#555](https://github.com/Leaflet/Leaflet/issues/555) - * Fixed a bug where `TileLayer` `load` event was firing only once (by [@lapinos03](https://github.com/lapinos03) and [shintonik](https://github.com/shintonik)). [#742](https://github.com/Leaflet/Leaflet/pull/742) [#177](https://github.com/Leaflet/Leaflet/issues/177) - * Fixed a bug where `FeatureGroup` popup events where not cleaned up after removing a layer from it (by [@danzel](https://github.com/danzel)). [#775](https://github.com/Leaflet/Leaflet/pull/775) - * Fixed a bug where `DomUtil.removeClass` didn't remove trailing spaces (by [@jieter](https://github.com/jieter)). [#784](https://github.com/Leaflet/Leaflet/pull/784) - * Fixed a bug where marker popup didn't take popup offset into account. - * Fixed a bug that led to an error when polyline was removed inside a `moveend` listener. - * Fixed a bug where `LayerGroup` `addLayer` wouldn't check if a layer has already been added (by [@danzel](https://github.com/danzel)). [798](https://github.com/Leaflet/Leaflet/pull/798) - -#### Browser bugfixes - - * Fixed broken zooming on IE10 beta (by [@danzel](https://github.com/danzel)). [#650](https://github.com/Leaflet/Leaflet/issues/650) [#751](https://github.com/Leaflet/Leaflet/pull/751) - * Fixed a bug that broke Leaflet for websites that had XHTML content-type header set (by [lars-sh](https://github.com/lars-sh)). [#801](https://github.com/Leaflet/Leaflet/pull/801) - * Fixed a bug that caused popups to be empty in IE when passing a DOM node as the content (by [@nrenner](https://github.com/nrenner)). [#472](https://github.com/Leaflet/Leaflet/pull/472) - * Fixed inability to use scrolled content inside popup due to mouse wheel propagation. - * Fixed a bug that caused jumping/stuttering of panning animation in some cases. - * Fixed a bug where popup size was calculated incorrectly in IE. - * Fixed a bug where cursor would flicker when dragging a marker. - * Fixed a bug where clickable paths on IE9 didn't have a hand cursor (by [naehrstoff](https://github.com/naehrstoff)). [#671](https://github.com/Leaflet/Leaflet/pull/671) - * Fixed a bug in IE with disappearing icons when changing opacity (by [@tagliala](https://github.com/tagliala) and [DamonOehlman](https://github.com/DamonOehlman)). [#667](https://github.com/Leaflet/Leaflet/pull/667) [#600](https://github.com/Leaflet/Leaflet/pull/600) - * Fixed a bug with setting opacity on IE10 (by [@danzel](https://github.com/danzel)). [796](https://github.com/Leaflet/Leaflet/pull/796) - * Fixed a bug where `Control.Layers` didn't work on IE7. [#652](https://github.com/Leaflet/Leaflet/issues/652) - * Fixed a bug that could cause false `mousemove` events on click in Chrome (by [@stsydow](https://github.com/stsydow)). [#757](https://github.com/Leaflet/Leaflet/pull/757) - * Fixed a bug in IE6-8 where adding fill or stroke on vector layers after initialization with `setStyle` would break the map. [#641](https://github.com/Leaflet/Leaflet/issues/641) - * Fixed a bug with setOpacity in IE where it would not work correctly if used more than once on the same element (by [@ajbeaven](https://github.com/ajbeaven)). [#827](https://github.com/Leaflet/Leaflet/pull/827) - * Fixed a bug in Chrome where transparent control corners sometimes couldn't be clicked through (by [@danzel](https://github.com/danzel)). [#836](https://github.com/Leaflet/Leaflet/pull/836) [#575](https://github.com/Leaflet/Leaflet/issues/575) - -#### Mobile browser bugfixes - - * Fixed a bug that sometimes caused map to disappear completely after zoom on iOS (by [@fr1n63](https://github.com/fr1n63)). [#580](https://github.com/Leaflet/Leaflet/issues/580) [#777](https://github.com/Leaflet/Leaflet/pull/777) - * Fixed a bug that often caused vector layers to flicker on drag end on iOS (by [@krawaller](https://github.com/krawaller)). [#18](https://github.com/Leaflet/Leaflet/issues/18) - * Fixed a bug with false map click events on pinch-zoom and zoom/layers controls click. [#485](https://github.com/Leaflet/Leaflet/issues/485) - * Fixed a bug where touching the map with two or more fingers simultaneously would raise an error. - * Fixed a bug where zoom control wasn't always visible on Android 3. [#335](https://github.com/Leaflet/Leaflet/issues/335) - * Fixed a bug where opening the layers control would propagate a click to the map (by [@jacobtoye](https://github.com/jacobtoye)). [#638](https://github.com/Leaflet/Leaflet/pull/638) - * Fixed a bug where `ImageOverlay` wouldn't stretch properly on zoom on Android 2. [#651](https://github.com/Leaflet/Leaflet/issues/651) - * Fixed a bug where `clearLayers` for vector layers on a Canvas backend (e.g. on Android 2) would take unreasonable amount of time. [#785](https://github.com/Leaflet/Leaflet/issues/785) - * Fixed a bug where `setLatLngs` and similar methods on vector layers on a Canvas backend would not update the layers immediately. [#732](https://github.com/Leaflet/Leaflet/issues/732) - -## 0.3.1 (February 14, 2012) - - * Fixed a regression where default marker icons wouldn't work if Leaflet include url contained a query string. - * Fixed a regression where tiles sometimes flickered with black on panning in iOS. - -## 0.3 (February 13, 2012) - -### Major features - - * Added **Canvas backend** for vector layers (polylines, polygons, circles). This enables vector support on Android < 3, and it can also be optionally preferred over SVG for a performance gain in some cases. Thanks to [@florianf](https://github.com/florianf) for a big part of this work. - * Added **layers control** (`Control.Layers`) for convenient layer switching. - * Added ability to set **max bounds** within which users can pan/zoom. [#93](https://github.com/Leaflet/Leaflet/issues/93) - -### Improvements - -#### Usability improvements - - * Map now preserves its center after resize. - * When panning to another copy of the world (that's infinite horizontally), map overlays now jump to corresponding positions. [#273](https://github.com/Leaflet/Leaflet/issues/273) - * Limited maximum zoom change on a single mouse wheel movement (so you won't zoom across the whole zoom range in one scroll). [#149](https://github.com/Leaflet/Leaflet/issues/149) - * Significantly improved line simplification performance (noticeable when rendering polylines/polygons with tens of thousands of points) - * Improved circles performance by not drawing them if they're off the clip region. - * Improved stability of zoom animation (less flickering of tiles). - -#### API improvements - - * Added ability to add a tile layer below all others (`map.addLayer(layer, true)`) (useful for switching base tile layers). - * Added `Map` `zoomstart` event (thanks to [@Fabiz](https://github.com/Fabiz)). [#377](https://github.com/Leaflet/Leaflet/pull/377) - * Improved `Map` `locate` method, added ability to watch location continuously and more options. [#212](https://github.com/Leaflet/Leaflet/issues/212) - * Added second argument `inside` to `Map` `getBoundsZoom` method that allows you to get appropriate zoom for the view to fit *inside* the given bounds. - * Added `hasLayer` method to `Map`. - * Added `Marker` `zIndexOffset` option to be able to set certain markers below/above others. [#65](https://github.com/Leaflet/Leaflet/issues/65) - * Added `urlParams` third optional argument to `TileLayer` constructor for convenience: an object with properties that will be evaluated in the URL template. - * Added `TileLayer` `continuousWorld` option to disable tile coordinates checking/wrapping. - * Added `TileLayer` `tileunload` event fired when tile gets removed after panning (by [@CodeJosch](https://github.com/CodeJosch)). [#256](https://github.com/Leaflet/Leaflet/pull/256) - * Added `TileLayer` `zoomOffset` option useful for non-256px tiles (by [@msaspence](https://github.com/msaspence)). - * Added `TileLayer` `zoomReverse` option to reverse zoom numbering (by [@Majiir](https://github.com/Majiir)). [#406](https://github.com/Leaflet/Leaflet/pull/406) - * Added `TileLayer.Canvas` `redraw` method (by [@mortenbekditlevsen](https://github.com/mortenbekditlevsen)). [#459](https://github.com/Leaflet/Leaflet/pull/459) - * Added `Polyline` `closestLayerPoint` method that's can be useful for interaction features (by [@anru](https://github.com/anru)). [#186](https://github.com/Leaflet/Leaflet/pull/186) - * Added `setLatLngs` method to `MultiPolyline` and `MultiPolygon` (by [@anru](https://github.com/anru)). [#194](https://github.com/Leaflet/Leaflet/pull/194) - * Added `getBounds` method to `Polyline` and `Polygon` (by [@JasonSanford](https://github.com/JasonSanford)). [#253](https://github.com/Leaflet/Leaflet/pull/253) - * Added `getBounds` method to `FeatureGroup` (by [@JasonSanford](https://github.com/JasonSanford)). [#557](https://github.com/Leaflet/Leaflet/pull/557) - * Added `FeatureGroup` `setStyle` method (also inherited by `MultiPolyline` and `MultiPolygon`). [#353](https://github.com/Leaflet/Leaflet/issues/353) - * Added `FeatureGroup` `invoke` method to call a particular method on all layers of the group with the given arguments. - * Added `ImageOverlay` `load` event. [#213](https://github.com/Leaflet/Leaflet/issues/213) - * Added `minWidth` option to `Popup` (by [@marphi](https://github.com/marphi)). [#214](https://github.com/Leaflet/Leaflet/pull/214) - * Improved `LatLng` constructor to be more tolerant (and throw descriptive error if latitude or longitude can't be interpreted as a number). [#136](https://github.com/Leaflet/Leaflet/issues/136) - * Added `LatLng` `distanceTo` method (great circle distance) (by [@mortenbekditlevsen](https://github.com/mortenbekditlevsen)). [#462](https://github.com/Leaflet/Leaflet/pull/462) - * Added `LatLngBounds` `toBBoxString` method for convenience (by [@JasonSanford](https://github.com/JasonSanford)). [#263](https://github.com/Leaflet/Leaflet/pull/263) - * Added `LatLngBounds` `intersects(otherBounds)` method (thanks to [@pagameba](https://github.com/pagameba)). [#350](https://github.com/Leaflet/Leaflet/pull/350) - * Made `LatLngBounds` `extend` method to accept other `LatLngBounds` in addition to `LatLng` (by [@JasonSanford](https://github.com/JasonSanford)). [#553](https://github.com/Leaflet/Leaflet/pull/553) - * Added `Bounds` `intersects(otherBounds)` method. [#461](https://github.com/Leaflet/Leaflet/issues/461) - * Added `L.Util.template` method for simple string template evaluation. - * Added `DomUtil.removeClass` method (by [@anru](https://github.com/anru)). - * Improved browser-specific code to rely more on feature detection rather than user agent string. - * Improved superclass access mechanism to work with inheritance chains of 3 or more classes; now you should use `Klass.superclass` instead of `this.superclass` (by [@anru](https://github.com/anru)). [#179](https://github.com/Leaflet/Leaflet/pull/179) - * Added `Map` `boxzoomstart` and `boxzoomend` events (by [@zedd45](https://github.com/zedd45)). [#554](https://github.com/Leaflet/Leaflet/pull/554) - * Added `Popup` `contentupdate` event (by [@mehmeta](https://github.com/mehmeta)). [#548](https://github.com/Leaflet/Leaflet/pull/548) - -#### Breaking API changes - - * `shiftDragZoom` map option/property renamed to `boxZoom`. - * Removed `mouseEventToLatLng` method (bringed back in 0.4). - -#### Development workflow improvements - - * Build system completely overhauled to be based on Node.js, Jake, JSHint and UglifyJS. - * All code is now linted for errors and conformity with a strict code style (with JSHint), and wont build unless the check passes. - -### Bugfixes - -#### General bugfixes - - * Fixed a bug where `Circle` was rendered with incorrect radius (didn't take projection exagerration into account). [#331](https://github.com/Leaflet/Leaflet/issues/331) - * Fixed a bug where `Map` `getBounds` would work incorrectly on a date line cross. [#295](https://github.com/Leaflet/Leaflet/issues/295) - * Fixed a bug where polygons and polylines sometimes rendered incorrectly on some zoom levels. [#381](https://github.com/Leaflet/Leaflet/issues/381) - * Fixed a bug where fast mouse wheel zoom worked incorrectly when approaching min/max zoom values. - * Fixed a bug where `GeoJSON` `pointToLayer` option wouldn't work in a `GeometryCollection`. [#391](https://github.com/Leaflet/Leaflet/issues/391) - * Fixed a bug with incorrect rendering of GeoJSON on a date line cross. [#354](https://github.com/Leaflet/Leaflet/issues/354) - * Fixed a bug where map panning would stuck forever after releasing the mouse over an iframe or a flash object (thanks to [@sten82](https://github.com/sten82)). [#297](https://github.com/Leaflet/Leaflet/pull/297) [#64](https://github.com/Leaflet/Leaflet/issues/64) - * Fixed a bug where mouse wheel zoom worked incorrectly if map is inside scrolled container (partially by [@chrillo](https://github.com/chrillo)). [#206](https://github.com/Leaflet/Leaflet/issues/206) - * Fixed a bug where it was possible to add the same listener twice. [#281](https://github.com/Leaflet/Leaflet/issues/281) - * Fixed a bug where `Circle` was rendered with incorrect radius (didn't take projection exaggeration into account). [#331](https://github.com/Leaflet/Leaflet/issues/331) - * Fixed a bug where `Marker` `setIcon` was not working properly (by [@marphi](https://github.com/marphi)). [#218](https://github.com/Leaflet/Leaflet/pull/218) [#311](https://github.com/Leaflet/Leaflet/issues/311) - * Fixed a bug where `Marker` `setLatLng` was not working if it's set before adding the marker to a map. [#222](https://github.com/Leaflet/Leaflet/issues/222) - * Fixed a bug where marker popup would not move on `Marker` `setLatLng` (by [@tjarratt](https://github.com/tjarratt)). [#272](https://github.com/Leaflet/Leaflet/pull/272) - * Fixed a bug where static properties of a child class would not override the parent ones. - * Fixed broken popup `closePopup` option (by [@jgerigmeyer](https://github.com/jgerigmeyer)). - * Fixed a bug that caused en error when dragging marker with icon without shadow (by [@anru](https://github.com/anru)). [#178](https://github.com/Leaflet/Leaflet/issues/178) - * Fixed a typo in `Bounds` `contains` method (by [@anru](https://github.com/anru)). [#180](https://github.com/Leaflet/Leaflet/pull/180) - * Fixed a bug where creating an empty `Polygon` with `new L.Polygon()` would raise an error. - * Fixed a bug where drag event fired before the actual movement of layer (by [@anru](https://github.com/anru)). [#197](https://github.com/Leaflet/Leaflet/pull/197) - * Fixed a bug where map click caused an error if dragging is initially disabled. [#196](https://github.com/Leaflet/Leaflet/issues/196) - * Fixed a bug where map `movestart` event would fire after zoom animation. - * Fixed a bug where attribution prefix would not update on `setPrefix`. [#195](https://github.com/Leaflet/Leaflet/issues/195) - * Fixed a bug where `TileLayer` `load` event wouldn't fire in some edge cases (by [@dravnic](https://github.com/dravnic)). - * Fixed a bug related to clearing background tiles after zooming (by [@neno-giscloud](https://github.com/neno-giscloud) & [@dravnic](https://github.com/dravnic)). - * Fixed a bug that sometimes caused map flickering after zoom animation. - * Fixed a bug related to cleaning up after removing tile layers (by [@dravnic](https://github.com/dravnic)). [#276](https://github.com/Leaflet/Leaflet/pull/276) - * Fixed a bug that made selecting text in the attribution control impossible. [#279](https://github.com/Leaflet/Leaflet/issues/279) - * Fixed a bug when initializing a map in a non-empty div. [#278](https://github.com/Leaflet/Leaflet/issues/278) - * Fixed a bug where `movestart` didn't fire on panning animation. - * Fixed a bug in Elliptical Mercator formula that affeted `EPSG:3395` CRS (by [@Savvkin](https://github.com/Savvkin)). [#358](https://github.com/Leaflet/Leaflet/pull/358) - -#### Browser bugfixes - - * Fixed occasional crashes on Mac Safari (thanks to [@lapinos03](https://github.com/lapinos03)). [#191](https://github.com/Leaflet/Leaflet/issues/191) - * Fixed a bug where resizing the map would sometimes make it blurry on WebKit (by [@mortenbekditlevsen](https://github.com/mortenbekditlevsen)). [#453](https://github.com/Leaflet/Leaflet/pull/453) - * Fixed a bug that raised error in IE6-8 when clicking on popup close button. [#235](https://github.com/Leaflet/Leaflet/issues/235) - * Fixed a bug with Safari not redrawing UI immediately after closing a popup. [#296](https://github.com/Leaflet/Leaflet/issues/296) - * Fixed a bug that caused performance drop and high CPU usage when calling `setView` or `panTo` to the current center. [#231](https://github.com/Leaflet/Leaflet/issues/231) - * Fixed a bug that caused map overlays to appear blurry in some cases under WebKit browsers. - * Fixed a bug that was causing errors in some Webkit/Linux builds (requestAnimationFrame-related), thanks to Chris Martens. - -#### Mobile browser bugfixes - - * Fixed a bug that caused an error when clicking vector layers under iOS. [#204](https://github.com/Leaflet/Leaflet/issues/204) - * Fixed crash on Android 3+ when panning or zooming (by [@florian](https://github.com/florianf)). [#137](https://github.com/Leaflet/Leaflet/issues/137) - * Fixed a bug on Android 2/3 that sometimes caused the map to disappear after zooming. [#69](https://github.com/Leaflet/Leaflet/issues/69) - * Fixed a bug on Android 3 that caused tiles to shift position on a big map. - * Fixed a bug that caused the map to pan when touch-panning inside a popup. [#452](https://github.com/Leaflet/Leaflet/issues/452) - * Fixed a bug that caused click delays on zoom control. - - -## 0.2.1 (2011-06-18) - - * Fixed regression that caused error in `TileLayer.Canvas`. - -## 0.2 (2011-06-17) - -### Major features - - * Added **WMS** support (`TileLayer.WMS` layer). - * Added different **projections** support, having `EPSG:3857`, `EPSG:4326` and `EPSG:3395` out of the box (through `crs` option in `Map`). Thanks to [@Miroff](https://github.com/Miroff) & [@Komzpa](https://github.com/Komzpa) for great advice and explanation regarding this. - * Added **GeoJSON** layer support. - -### Improvements - -#### Usability improvements - - * Improved panning performance in Chrome and FF considerably with the help of `requestAnimationFrame`. [#130](https://github.com/Leaflet/Leaflet/issues/130) - * Improved click responsiveness in mobile WebKit (now it happens without delay). [#26](https://github.com/Leaflet/Leaflet/issues/26) - * Added tap tolerance (so click happens even if you moved your finger slighly when tapping). - * Improved geolocation error handling: better error messages, explicit timeout, set world view on locateAndSetView failure. [#61](https://github.com/Leaflet/Leaflet/issues/61) - -#### API improvements - - * Added **MultiPolyline** and **MultiPolygon** layers. [#77](https://github.com/Leaflet/Leaflet/issues/77) - * Added **LayerGroup** and **FeatureGroup** layers for grouping other layers. - * Added **TileLayer.Canvas** for easy creation of canvas-based tile layers. - * Changed `Circle` to be zoom-dependent (with radius in meters); circle of a permanent size is now called `CircleMarker`. - * Added `mouseover` and `mouseout` events to map, markers and paths; added map `mousemove` event. - * Added `setLatLngs`, `spliceLatLngs`, `addLatLng`, `getLatLngs` methods to polylines and polygons. - * Added `setLatLng` and `setRadius` methods to `Circle` and `CircleMarker`. - * Improved `LatLngBounds contains` method to accept `LatLng` in addition to `LatLngBounds`, the same for `Bounds contains` and `Point` - * Improved `LatLngBounds` & `Bounds` to allow their instantiation without arguments (by [@snc](https://github.com/snc)). - * Added TMS tile numbering support through `TileLayer` `scheme: 'tms'` option (by [@tmcw](https://github.com/tmcw)). - * Added `TileLayer` `noWrap` option to disable wrapping `x` tile coordinate (by [@jasondavies](https://github.com/jasondavies)). - * Added `opacity` option and `setOpacity` method to `TileLayer`. - * Added `setLatLng` and `setIcon` methods to `Marker`. - * Added `title` option to `Marker`. - * Added `maxZoom` argument to `map.locateAndSetView` method. - * Added ability to pass Geolocation options to map `locate` and `locateAndSetView` methods (by [@JasonSanford](https://github.com/JasonSanford)). - * Improved `Popup` to accept HTML elements in addition to strings as its content. - -#### Development workflow improvements - - * Added `Makefile` for building `leaflet.js` on non-Windows machines (by [@tmcw](https://github.com/tmcw)). - * Improved `debug/leaflet-include.js` script to allow using it outside of `debug` folder (by [@antonj](https://github.com/antonj)). - * Improved `L` definition to be compatible with CommonJS. [#122](https://github.com/Leaflet/Leaflet/issues/122) - -### Bug fixes - -#### General bugfixes - - * Fixed a bug where zooming is broken if the map contains a polygon and you zoom to an area where it's not visible. [#47](https://github.com/Leaflet/Leaflet/issues/47) - * Fixed a bug where closed polylines would not appear on the map. - * Fixed a bug where marker that was added, removed and then added again would not appear on the map. [#66](https://github.com/Leaflet/Leaflet/issues/66) - * Fixed a bug where tile layer that was added, removed and then added again would not appear on the map. - * Fixed a bug where some tiles would not load when panning across the date line. [#97](https://github.com/Leaflet/Leaflet/issues/97) - * Fixed a bug where map div with `position: absolute` is reset to `relative`. [#100](https://github.com/Leaflet/Leaflet/issues/100) - * Fixed a bug that caused an error when trying to add a marker without shadow in its icon. - * Fixed a bug where popup content would not update on `setContent` call. [#94](https://github.com/Leaflet/Leaflet/issues/94) - * Fixed a bug where double click zoom wouldn't work if popup is opened on map click - * Fixed a bug with click propagation on popup close button. [#99](https://github.com/Leaflet/Leaflet/issues/99) - * Fixed inability to remove ImageOverlay layer. - -#### Browser bugfixes - - * Fixed a bug where paths would not appear in IE8. - * Fixed a bug where there were occasional slowdowns before zoom animation in WebKit. [#123](https://github.com/Leaflet/Leaflet/issues/123) - * Fixed incorrect zoom animation & popup styling in Opera 11.11. - * Fixed popup fade animation in Firefox and Opera. - * Fixed a bug where map isn't displayed in Firefox when there's an `img { max-width: 100% }` rule. - -#### Mobile browsers bugfixes - - * Fixed a bug that prevented panning on some Android 2.1 (and possibly older) devices. [#84](https://github.com/Leaflet/Leaflet/issues/84) - * Disabled zoom animation on Android by default because it's buggy on some devices (will be enabled back when it's stable enough). [#32](https://github.com/Leaflet/Leaflet/issues/32) - * Fixed a bug where map would occasionally break while multi-touch-zooming on iOS. [#32](https://github.com/Leaflet/Leaflet/issues/32) - * Fixed a bug that prevented panning/clicking on Android 3 tablets. [#121](https://github.com/Leaflet/Leaflet/issues/121) - * Fixed a bug that prevented panning/clicking on Opera Mobile. [#138](https://github.com/Leaflet/Leaflet/issues/138) - * Fixed potentional memory leak on WebKit when removing tiles, thanks to [@Scalar4eg](https://github.com/Scalar4eg). [#107](https://github.com/Leaflet/Leaflet/issues/107) - -## 0.1 (2011-05-13) - -Initial Leaflet release. diff --git a/www/manual_lib/leaflet/CONTRIBUTING.md b/www/manual_lib/leaflet/CONTRIBUTING.md deleted file mode 100644 index 052240d19..000000000 --- a/www/manual_lib/leaflet/CONTRIBUTING.md +++ /dev/null @@ -1,155 +0,0 @@ -Contributing to Leaflet -======================= - - 1. [Getting Involved](#getting-involved) - 2. [Reporting Bugs](#reporting-bugs) - 3. [Contributing Code](#contributing-code) - 4. [Improving Documentation](#improving-documentation) - -## Getting Involved - -Third-party patches are absolutely essential on our quest to create the best mapping library that will ever exist. -However, they're not the only way to get involved with the development of Leaflet. -You can help the project tremendously by discovering and [reporting bugs](#reporting-bugs), -[improving documentation](#improving-documentation), -helping others on the [Leaflet forum](https://groups.google.com/forum/#!forum/leaflet-js) -and [GitHub issues](https://github.com/Leaflet/Leaflet/issues), -showing your support for your favorite feature suggestions on [Leaflet UserVoice page](http://leaflet.uservoice.com), -tweeting to [@LeafletJS](http://twitter.com/LeafletJS) -and spreading the word about Leaflet among your colleagues and friends. - -## Reporting Bugs - -Before reporting a bug on the project's [issues page](https://github.com/Leaflet/Leaflet/issues), -first make sure that your issue is caused by Leaflet, not your application code -(e.g. passing incorrect arguments to methods, etc.). -Second, search the already reported issues for similar cases, -and if it's already reported, just add any additional details in the comments. - -After you made sure that you've found a new Leaflet bug, -here are some tips for creating a helpful report that will make fixing it much easier and quicker: - - * Write a **descriptive, specific title**. Bad: *Problem with polylines*. Good: *Doing X in IE9 causes Z*. - * Include **browser, OS and Leaflet version** info in the description. - * Create a **simple test case** that demonstrates the bug (e.g. using [JSFiddle](http://jsfiddle.net/)). - * Check whether the bug can be reproduced in **other browsers**. - * Check if the bug occurs in the stable version, master, or both. - * *Bonus tip:* if the bug only appears in the master version but the stable version is fine, - use `git bisect` to find the exact commit that introduced the bug. - -If you just want some help with your project, -try asking [on the Leaflet forum](https://groups.google.com/forum/#!forum/leaflet-js) instead. - -## Contributing Code - -### Considerations for Accepting Patches - -While we happily accept patches, we're also commited to keeping Leaflet simple, lightweight and blazingly fast. -So bugfixes, performance optimizations and small improvements that don't add a lot of code -are much more likely to get accepted quickly. - -Before sending a pull request with a new feature, first check if it's been discussed before already -(either on [GitHub issues](https://github.com/Leaflet/Leaflet/issues) -or [Leaflet UserVoice](http://leaflet.uservoice.com/)), -and then ask yourself two questions: - - 1. Are you sure that this new feature is important enough to justify its presense in the Leaflet core? - Or will it look better as a plugin in a separate repository? - 2. Is it written in a simple, concise way that doesn't add bulk to the codebase? - -If your feature or API improvement did get merged into master, -please consider submitting another pull request with the corresponding [documentation update](#improving-documentation). - -### Setting up the Build System - -To set up the Leaflet build system, install [Node](http://nodejs.org/), -then run the following commands in the project root: - -``` -npm install -g jake -npm install -``` - -You can build minified Leaflet by running `jake` (it will be built from source in the `dist` folder). -For a custom build with selected components, open `build/build.html` in the browser and follow the instructions from there. - -### Making Changes to Leaflet Source - -If you're not yet familiar with the way GitHub works (forking, pull requests, etc.), -be sure to check out the awesome [article about forking](https://help.github.com/articles/fork-a-repo) -on the GitHub Help website — it will get you started quickly. - -You should always write each batch of changes (feature, bugfix, etc.) in **its own topic branch**. -Please do not commit to the `master` branch, or your unrelated changes will go into the same pull request. - -You should also follow the code style and whitespace conventions of the original codebase. -In particular, use tabs for indentation and spaces for alignment. - -Before commiting your changes, run `jake lint` to catch any JS errors in the code and fix them. -If you add any new files to the Leaflet source, make sure to also add them to `build/deps.js` -so that the build system knows about them. - -Also, please make sure that you have [line endings configured properly](https://help.github.com/articles/dealing-with-line-endings) in Git! Otherwise the diff will show that all lines of a file were changed even if you touched only one. - -Happy coding! - -## Running the Tests - -To run the tests from the command line, -install [PhantomJS](http://phantomjs.org/) (and make sure it's in your `PATH`), -then run: - -``` -jake test -``` - -To run all the tests in actual browsers at the same time, you can do: - -``` -jake test --ff --chrome --safari --ie -``` - -To run the tests in a browser manually, open `spec/index.html`. - -## Code Coverage - -To generate a detailed report about test coverage (which helps tremendously when working on test improvements), run: - -``` -jake test --cov -``` - -After that, open `spec/coverage//index.html` in a browser to see the report. -From there you can click through folders/files to get details on their individual coverage. - -## Improving Documentation - -The code of the live Leaflet website that contains all documentation and examples is located in the `gh-pages` branch -and is automatically generated from a set of HTML and Markdown files by [Jekyll](https://github.com/mojombo/jekyll). - -The easiest way to make little improvements such as fixing typos without even leaving the browser -is by editing one of the files with the online GitHub editor: -browse the [gh-pages branch](https://github.com/Leaflet/Leaflet/tree/gh-pages), -choose a certain file for editing (e.g. `reference.html` for API reference), -click the Edit button, make changes and follow instructions from there. -Once it gets merged, the changes will immediately appear on the website. - -If you need to make edits in a local repository to see how it looks in the process, do the following: - - 1. [Install Ruby](http://www.ruby-lang.org/en/) if don't have it yet. - 2. Run `gem install jekyll`. - 3. Run `jekyll serve --watch` in the root `Leaflet` folder. - 4. Open `localhost:4000` in your browser. - -Now any file changes will be updated when you reload pages automatically. -After commiting the changes, just send a pull request. - -If you need to update documentation according to a new feature that only appeared in the master version (not stable one), -you need to make changes to `gh-pages-master` branch instead of `gh-pages`. -It will get merged into the latter when released as stable. - -## Thank You - -Not only are we grateful for any contributions, — helping Leaflet and its community actually makes you AWESOME. -Join [this approved list of awesome people](https://github.com/Leaflet/Leaflet/graphs/contributors) -and help us push the limits of what's possible with online maps! diff --git a/www/manual_lib/leaflet/Jakefile.js b/www/manual_lib/leaflet/Jakefile.js deleted file mode 100644 index 77be075b4..000000000 --- a/www/manual_lib/leaflet/Jakefile.js +++ /dev/null @@ -1,48 +0,0 @@ -/* -Leaflet building, testing and linting scripts. - -To use, install Node, then run the following commands in the project root: - - npm install -g jake - npm install - -To check the code for errors and build Leaflet from source, run "jake". -To run the tests, run "jake test". - -For a custom build, open build/build.html in the browser and follow the instructions. -*/ - -var build = require('./build/build.js'); - -function hint(msg, paths) { - return function () { - console.log(msg); - jake.exec('node node_modules/jshint/bin/jshint -c ' + paths, - {printStdout: true}, function () { - console.log('\tCheck passed.\n'); - complete(); - }); - } -} - -desc('Check Leaflet source for errors with JSHint'); -task('lint', {async: true}, hint('Checking for JS errors...', 'build/hintrc.js src')); - -desc('Check Leaflet specs source for errors with JSHint'); -task('lintspec', {async: true}, hint('Checking for specs JS errors...', 'spec/spec.hintrc.js spec/suites')); - -desc('Combine and compress Leaflet source files'); -task('build', {async: true}, function () { - build.build(complete); -}); - -desc('Run PhantomJS tests'); -task('test', ['lint', 'lintspec'], {async: true}, function () { - build.test(complete); -}); - -task('default', ['test', 'build']); - -jake.addListener('complete', function () { - process.exit(); -}); diff --git a/www/manual_lib/leaflet/LICENSE b/www/manual_lib/leaflet/LICENSE deleted file mode 100644 index 46cd121fe..000000000 --- a/www/manual_lib/leaflet/LICENSE +++ /dev/null @@ -1,23 +0,0 @@ -Copyright (c) 2010-2013, Vladimir Agafonkin -Copyright (c) 2010-2011, CloudMade -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are -permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, this list of - conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright notice, this list - of conditions and the following disclaimer in the documentation and/or other materials - provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY -EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE -COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) -HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR -TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/www/manual_lib/leaflet/PLUGIN-GUIDE.md b/www/manual_lib/leaflet/PLUGIN-GUIDE.md deleted file mode 100644 index e9325e570..000000000 --- a/www/manual_lib/leaflet/PLUGIN-GUIDE.md +++ /dev/null @@ -1,127 +0,0 @@ -# Leaflet Plugin Authoring Guide - -One of the greatest things about Leaflet is its powerful plugin ecosystem. -The [Leaflet plugins page](http://leafletjs.com/plugins.html) lists dozens of awesome plugins, and more are being added every week. - -This guide lists a number of best practices for publishing a Leaflet plugin that meets the quality standards of Leaflet itself. - -1. [Presentation](#presentation) - - [Repository](#repository) - - [Name](#name) - - [Demo](#demo) - - [Readme](#readme) - - [License](#license) -2. [Code](#code) - - [File Structure](#file-structure) - - [Code Conventions](#code-conventions) - - [Plugin API](#plugin-api) - -## Presentation - -### Repository - -The best place to put your Leaflet plugin to is a separate [GitHub](http://github.com) repository. -If you create a collection of plugins for different uses, -don't put them in one repo — -it's usually easier to work with small, self-contained plugins in individual repositories. - -### Name - -Most existing plugins follow the convention of naming plugins (and repos) like this: `Leaflet.MyPluginName`. -You can use other forms (e.g. "leaflet-my-plugin-name"), -just make sure to include the word "Leaflet" in the name so that it's obvious that it's a Leaflet plugin. - -### Demo - -The most essential thing to do when publishing a plugin is to include a demo that showcases what the plugin does — -it's usually the first thing people will look for. - -The easiest way to put up a demo is using [GitHub Pages](http://pages.github.com/). -A good [starting point](https://help.github.com/articles/creating-project-pages-manually) is creating a `gh-pages` branch in your repo and adding an `index.html` page to it — -after pushing, it'll be published as `http://.github.io/`. - -### Readme - -The next thing you need to have is a descriptive `README.md` in the root of the repo (or a link to a website with a similar content). -At a minimum it should contain the following items: - -- name of the plugin -- a simple, concise description of what it does -- requirements - - Leaflet version - - other external dependencies (if any) - - browser / device compatibility -- links to demos -- instructions for including the plugin -- simple usage code example -- API reference (methods, options, events) - -### License - -Every open source repository should include a license. -If you don't know what open source license to choose for your code, -[MIT License](http://opensource.org/licenses/MIT) and [BSD 2-Clause License](http://opensource.org/licenses/BSD-2-Clause) are both good choices. -You can either put it in the repo as a `LICENSE` file or just link to the license from the Readme. - -## Code - -### File Structure - -Keep the file structure clean and simple, -don't pile up lots of files in one place — -make it easy for a new person to find their way in your repo. - -A barebones repo for a simple plugin would look like this: - -``` -my-plugin.js -README.md -``` - -An example of a more sophisticated plugin file structure: - -``` -/src - JS source files -/dist - minified plugin JS, CSS, images -/spec - test files -/lib - any external libraries/plugins if necessary -/examples - HTML examples of plugin usage -README.md -LICENSE -package.json -``` - -### Code Conventions - -Everyone's tastes are different, but it's important to be consistent with whatever conventions you choose for your plugin. - -For a good starting point, check out [Airbnb JavaScript Guide](https://github.com/airbnb/javascript). -Leaflet follows pretty much the same conventions -except for using smart tabs (hard tabs for indentation, spaces for alignment) -and putting a space after the `function` keyword. - -### Plugin API - -Never expose global variables in your plugin.
-If you have a new class, put it directly in the `L` namespace (`L.MyPlugin`).
-If you inherit one of the existing classes, make it a sub-property (`L.TileLayer.Banana`).
-If you want to add new methods to existing Leaflet classes, you can do it like this: `L.Marker.include({myPlugin: …})`. - -Function, method and property names should be in `camelCase`.
-Class names should be in `CapitalizedCamelCase`. - -If you have a lot of arguments in your function, consider accepting an options object instead -(putting default values where possible so that users don't need specify all of them): - -```js -// bad -marker.myPlugin('bla', 'foo', null, {}, 5, 0); - - // good -marker.myPlugin('bla', { - optionOne: 'foo', - optionThree: 5 -}); -``` - -And most importantly, keep it simple. Leaflet is all about *simplicity*. diff --git a/www/manual_lib/leaflet/README.md b/www/manual_lib/leaflet/README.md deleted file mode 100644 index 220b74ecc..000000000 --- a/www/manual_lib/leaflet/README.md +++ /dev/null @@ -1,34 +0,0 @@ -Leaflet - -Leaflet is an open source JavaScript library for **mobile-friendly interactive maps**. -It is developed by [Vladimir Agafonkin][] of [MapBox][] with a team of dedicated [contributors][]. -Weighing just about 30 KB of gzipped JS code, it has all the [features][] most developers ever need for online maps. - -Leaflet is designed with *simplicity*, *performance* and *usability* in mind. -It works efficiently across all major desktop and mobile platforms out of the box, -taking advantage of HTML5 and CSS3 on modern browsers while being accessible on older ones too. -It can be extended with a huge amount of [plugins][], -has a beautiful, easy to use and [well-documented][] API -and a simple, readable [source code][] that is a joy to [contribute][] to. - -For more info, docs and tutorials, check out the [official website][].
-For **Leaflet downloads** (including the built master version), check out the [download page][]. - -We're happy to meet new contributors. -If you want to **get involved** with Leaflet development, check out the [contribution guide][contribute]. -Let's make the best mapping library that will ever exist, -and push the limits of what's possible with online maps! - -[![Build Status](https://travis-ci.org/Leaflet/Leaflet.png?branch=master)](https://travis-ci.org/Leaflet/Leaflet) - - [Vladimir Agafonkin]: http://agafonkin.com/en - [contributors]: https://github.com/Leaflet/Leaflet/graphs/contributors - [features]: http://leafletjs.com/features.html - [plugins]: http://leafletjs.com/plugins.html - [well-documented]: http://leafletjs.com/reference.html "Leaflet API reference" - [source code]: https://github.com/Leaflet/Leaflet "Leaflet GitHub repository" - [hosted on GitHub]: http://github.com/Leaflet/Leaflet - [contribute]: https://github.com/Leaflet/Leaflet/blob/master/CONTRIBUTING.md "A guide to contributing to Leaflet" - [official website]: http://leafletjs.com - [download page]: http://leafletjs.com/download.html - [MapBox]: https://mapbox.com diff --git a/www/manual_lib/leaflet/bower.json b/www/manual_lib/leaflet/bower.json deleted file mode 100644 index 001fcf183..000000000 --- a/www/manual_lib/leaflet/bower.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "name": "leaflet", - "version": "0.7.7", - "description": "JavaScript library for mobile-friendly interactive maps", - "main": [ - "dist/leaflet.css", - "dist/leaflet-src.js", - "dist/images/layers-2x.png", - "dist/images/layers.png", - "dist/images/marker-icon-2x.png", - "dist/images/marker-icon.png", - "dist/images/marker-shadow.png" - ], - "ignore": [ - ".*", - "CHANGELOG.json", - "FAQ.md", - "debug", - "spec", - "src", - "build" - ] -} diff --git a/www/manual_lib/leaflet/component.json b/www/manual_lib/leaflet/component.json deleted file mode 100644 index 2bef5e904..000000000 --- a/www/manual_lib/leaflet/component.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "name": "leaflet", - "version": "0.7.7", - "description": "JavaScript library for mobile-friendly interactive maps", - "scripts": [ - "dist/leaflet.js", - "dist/leaflet-src.js" - ], - "images": [ - "dist/images/layers-2x.png", - "dist/images/layers.png", - "dist/images/marker-icon-2x.png", - "dist/images/marker-icon.png", - "dist/images/marker-shadow.png" - ], - "styles": [ - "dist/leaflet.css" - ], - "main": "dist/leaflet-src.js" -} diff --git a/www/manual_lib/leaflet/dist/images/layers-2x.png b/www/manual_lib/leaflet/dist/images/layers-2x.png deleted file mode 100644 index a2cf7f9efef65d2e021f382f47ef50d51d51a0df..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2898 zcmV-Y3$65tP)?AfzNU07Ji0>J$I zyy*J%>jA&t|KY2zz8cz!dNXf;;xfzYhMv6otBB#?C3IqawZEtV)Ws@UgL!F(S zVuQi(g3)MfC@U-DvZ*wkrlzJCm&-NacDq09>gq~l5}T2sGiS~m&}cNz)Ya8VDT)#l zNC*+dVzFibkV>Wf6h#RdO+pCebUI^xzyIT7$BqeRmmotYPo7ln-o5)Lb#-+Wt4tB1 zL?WS%$KwYGA#wnqC~8q6kz5js#Q~u?=I7@{PN#EXe0=;bLfDnk&?-~(di{aQ%F2}6 z@Otq)pTDxQa)9Ug-O2u^X?k2HlU<@|dP!(bpU+2oJf2JG*tMadci(-tUaeLiZfIyI zNXL}*ZH>iZbu7y^5kgWvyHOOC5Q#)KsZ{C&ASge}vh={fz(ODpIRDBkuQ-zCz2DG@ z6DQ<4o$iRqWHRj7u|x2JWLdT}9*;l4^Za(9F#tf*^mh`8#Vh4?g(dDVl2B@enN;WQv=CFQPhf9EWRp{ zNIXJgB9Vy5;c(oXn3y=%-rnw`&Ye4V)Mzv|l$VzaHo|e-_E;?T1kdxO*)=`2Xqpa6 zrP7NG!+a++W^!^;hrf`@B%%6jB1%hvEb zFJ>4fL{U`QO=E0qtk7<^KSgzPbPxbBg+g)p>8GEbC@wBeYV3ZdJSwGQ*R5N(WS@NU zNkupuZUrD^T3cIt2q6ce(P*R7=`5L>n_JN7bW0RVDKOzL<*owE|)*| z=9_Ph+_P37C(~njkHQ666opafyd+FS(c>%d`Sp- z`JH#(8C@+SS|9N2v(JVZh6&ubaf8_Hc6w-N2$PeOXliOgb#?V4H?UqKBO|ccY?z;) zhfF4;&1N%EsZ;@u*D=RA~Dk?%tOA8c=4VUv}hGC8|TCMgUDwV34 zrs<>$B{w%0TCEl`nGC^T5K~iA2m}Ji&(FuUZQHiQ%*4b5KL7l4_AkZ2nK`j`Fyy2 z`!Kkw^p=FJ44nUmup2m!VRr@Z^(ELa9_@6(h;y^ZEL^ySv4Ui;H!u96I#v zx8Iulet&Oyc{weSNRq-+EEYqhQlX@z1T!-;2nK`jdc6PurBeA&W*iO&zWVAbghCjHZwG}lrH7Pr5d3kyIv(G*o9v>e!1DK_0`Y=TZ!5eS9AzNHr{1t#-0$?jED{U<; zEss+aCE6$%&+`}>8iL#H2FGzIEiJ{qefu&t77B&X)6;`sFbIZWU@#a^TU(oQjS@oG zzP`RIKA*1%cXsNx<#PF3ufP8K%7z@u%gc+I&1Px31}-ctz-F@{6beBs7DKPs-EPOq$_fe#3sbV|KBl0tu@My&6)E$_Vlnjh z_hWK$5)z37)z#HdDwY2N(B9V8Hu->|?(XjA0i48L4zVl?uh+Ylz+^I^s;VmG;!MXb z0Ze&7gb<95j$&|d5UU-m)9D}*t*wS70KWlns;#Y!r7m2!Py^tP0KT6r;ljcKTrL+D z7Z-)F0KkLns;#XB01OQc31!LydE|0Aj7DRsDR~{hPnqiK>c8#Sv12d8FgeLeNu^Sh zm6bsvksuTb!RPZK8jWJ-&Yc@B++^&Uo}L!W6qaRSx7%T}*^o#iP*qh0qtOVNY~vSW zj^pG`r&CXLbaW&DENHb_w??CRe8ULbna3WF2RCotL{3f)_U_#awOXAj1kq>|cDo$_ z(Ae0BoSdZnwx&QJfNR&Tt#z7SuTQ&vr>Cd;T`pHCA*77z=;&wz@E(9lu~_VEYHG@t z%jK1+5`@EH3=a>lRcbbyk)NNRveI-~T3SMHZ|_=X)zs9aos!XLblPUKO-7?pGXNie zmnlLBEEbClz$%C6l9G}ud-m*UVHjq^dBO8M{C+h5~JRXF@VdUrMqot)qFkC~S5c>N1u(Y%Ug+c+nUXQ%Iyp%EFaCp$+a7a0hs{-&P zfS0XSYjO^)Gxi*S-vij0latfi)YMd-lasS6UE@YZMj(V;8!#oMkwhXfXSdsj78Vv- z0n7mSxz%d@`~BrMJPNj0EQJ8N02~7lEh{Ut84QM$k3;F$C4ebO<@ft9kByDh0N4iL z41i9n)jFT7Y}(rgi^bA>H%SA-Fr)SL^)ZD)VM-N~j9maSVG00XadFXSv)Pssi9{WM z0RYFWR%?H%7(v%57K?=ea2&vI0musq3NAM`Hr9&8;tgM42_cxAoW$7J7 zXf#RRbXT>?E&v%b1;9T6{LE^#3O>ls>W z1%Om4^+QKT$He~%>hA6?ZftBk<8ry0&1N$IV0CpB>2x|AjYe;Fc6L7h&!E1(zLV9} z)u*ghYw33S?Ck9Fgo=++wEZ(=B3H#x{g#TB~MOH_MSa^ zc4|)`Ns{=6hK6>J$8)^2w3OYbQA&$)x!mgjU^1EhAcSN$>dVW^nk>r$u~@866vh0G zpj)?YHF`XrckFh1+18Bm`FyRSC@qvyBLEOW)(i&25YO}DTWx1%W}eBi{Nw42!K@e0==o zxpU{{$nD#=-|~9BZwP{5+EOON+S*#Ps;cz>Ufv`?=QwW6Xf%ciA<9N!VPPScOeTM2 z-EQ}HPN#E85Cpv-DvILC<#KQ7y6yx(c7Xr@(RKZxs;V`FkY$!-7Yf4T$B&Ed-o1N< zZE9+oefaR<2dPx*`JqFH463TWsVGVi0KW&o*2Qa@R;_7TrK+m4y}iAba5&toD9UGq zQi`6Qp4W6;?^|76J$~%iG2-=lUxD$@N+y%IckdoGo6Q3Z!?d42e}0ifqtTO;(yIXc zOG`@#hr=i-DM4#%D-IkuurEL+lfmHNAXZjZ(A?Y%i^T!}aYD$4ti$2>-r;b#3kZ@&v(P5LT;o-DhrY4v|QNvMf8u^L+b-3m2Y|J9qB10=NpGer06^@pv5N<>feX zg(&*Cs5aQjE#+9YHA8TpAUi{Y=lqVzkffYD9SGYK9?lv`KH@j6va9K z-w1+$Kp+s{IIgtNqjWlrr%#_E5C{MOMn*5}%e7uUP19CmvDon3+#Ch)u_Q@< z7GnSFJrYHc0C=AeBKmy3#j2{RmV%bcAKzn;9E(O zHU-}Cg%w4y9Ke@Gqw#Ps7_=4_7gud(m(6BpB9X|WY&JU%;8RJG=C`xk_0J%RVjCgk zE1S)hsjI7NVHm~;0F+WS9*+-BPfwdErJa%_gh876I}?PQWpJLz%)x;}A1s3+;FijJ6nrW+Pl4)+EiN1Z`Z};D5lx0BtvZnmddk_DqORVPG3@A z|MUAQ5d8CyG`n3U%W5w|$1lmUI>14Eit;<8S?vK{s*?{-Ss+T)u_t92ZJTA8?H?iF zR>;v&x7=gkU3dZlw!Q;_2%o}};F13pC@6@Z$Rj?JWwli(vf7`Uv_M3vmPaI6ZRyg? zwr>!?ft(K4bi>Np0r=D2_w3@8-GdNOt_Q!(r!eStxP|AMG^4f1MRn*m6B>vlqxDrZ z^e+Su+;WdVxV9T!t{sF|>)yKqtLo0f%X=)K?{|}VWzP^q==9)`cMLdQ#3#~>wy4qc zkwZdrRrSA+s#>ZLK#*s&!Gi5)Vb$&-com)GuwvIBL{{}fScMrv%gqq1Gu;L{wqS=D zA}ae~dCefKx&Wue^ipzWJZ7j zXOrbS%~*l+4B-|15TG$lD8hF1;}EmhTVCA{%ItO^Ul121NsW&?6bK%9NRoQ!5CUZB zO|YcG$Vgw>H3Xqp1%I_^QV@c+R-jF?y|mH7qa2-(C z0ugQ8pDRw<4{n()NIJyegIV${HQGfO5|ixWN;7!nv;%PvB8%H$$MGRJ`}fQ6#kbes z>h&MMcTZrm#Ts3`fhrQak0q-hmbwneh)8_kw~}aV#&vv&0DQ zTMfe^L}O-h6u4_rJ&^vk4ik*_)7p25=@J%{bu-Se@_xIv$v4hVrK*YPiWBP+oJ5Ir zr3moEi=@SPav_d;H&n2Pu<`*W>zjWJNOw_DD_r~j28`tsSACjsxMemoPU@AB>{HW| ztXJMqrYlUW(>mdwMq$Dp@GE$mom`;n2e&N-yI52)$YiOCq+5IXJdE|zd*KS>5aSRb z&c)UdVb4DKNOFD!$C<8h{hnqg;riV@!i3$}=UGTOZpIU)>0{iquGsT|d?Y#Yne-5SPQrxRe+$>w;#JvMh{Q|>l$k-X z*)S}8wwajRf-*gjo*13Ddi{I2mrq!J6XOcRiG#RlA-3m(|8_HzBcDkRaoI^2U;8Bj zLQ1_>oIw~*j8y0k)gb88Fw%SV$TO(&Ik0F^e6@= zLHw>E1o&f_sL`n+G87&T9yqi}E?j2>(j)xilP|{{#Ely_L7r5{ctW;yF>b25Js}>`iO75R6BpgcE9|%%7ZRzD#1@K!W4(uK@LfLHB`NAX3qZf^YwSvp;i9@cqQ*)vIMW(V~k@y^(GFR zk?hjYBY8Jfi-jYuvcKGw#YY%vDItj}3 z7Q|uPsUF8INEZfRw#oQYFK+5{*aoL3O>O}4)g`9<@EtcFTw-*g{8$|m2r9KG(G1~; z5e{y}MqI4=Zwu&dpd`7ElAEf=5>(R5d?a55G39=D1mdJp{meN=dkKNp1|7_pf2kQ< za(hP&%AULsujtTO-x4$UA&=)46DW!dAjWf}ei8-FW91wTuZPe2cpnffC0y4@sv2)Mw;_ci|bZ`gPMKR{MfO zKlGq*A1TRFnjioxLQU_S-3#-w^pgr|akh3F*-@`3{jraTr2X0$DxU9J6 zonZ#3S7xR6ObDnNWJ8&AnybbQ=UC0Wae1hQ7p*{c(l)9RmncZ49Yhd#w`%) zJK~gOp5Ur+-DQnt#)LdUN8^=@2-enu2QF9ys>*XI-S-6QHw&K;_-m@Idn%23!X5>r z@k-;CZ74HNf_oumFy8=wOzyrX$n%YiOPc-`SB%=YvR_CYcdtRU%#lH0jzd^#(k@-di-hx~al>I_R&DnN#rm07DYJ+aF!NQPu( zbl)m=2e-pbn6kGOq%ozxMkhXFRl&@1RiUgum3Vj1u#)6jsv%5j<*IR6^t$emDShpN z7o|>QRl&?k@XAh_XN1|9@o5QNcLkjz8A*rcE*n}g+c*p5 z7~m;%`pNaTgO1TTk`ZiZ=Bn}0^D(8ryf5D9p^RE?AC-e7yN3;(S*bnf{JGme)u3~( zS$ORcqqFvg`t|$f)g;O&W!6%aW^l!m_k7b2$D02GPgh9AD1`()~cZ8Oj2AQyau(pP%|J;>TN`^P;r=4@@A|s=UjbU%Sr& zOCYBon0Iw=*%^D@^5cwU6_3(-JaBP001cn1^@s6z>|W`000J>NklgF+#9zZY7a#;@J(5X0e&McXK2n7+jhR}<0i-1U5t`>D@ zJSJ*^swjdwq0keUf9!BETXZhVyjqS4&z|?2HdJnOU-HYF_xSyu=XsCkdtVv=(53>u zME@3F*5J;OHwJNJdWK(ivQ??rr&t7M)1yRas=d_yYH>g+p#{( zm+NoyW%|8bNfUkAMrabri(FY#Dqr5%zhZA&e^iALHXiJOFYA7Qt##L_a?_z6SW{&J zVeyp#G&snW>SO{*%d9CGVM}xic~V`MU$)*JU1Nbw2YX?ywi}|VZ4g;$g)p^+DoLHR zZ^Zr$S_=f^oU`+!4K^?NsU;H{;bhhex#H7(!s52U&FJ}OHQf-VvVd?Btj2MhF|zQI z%l~jBr~6T7^_WIHC1>8j&bv`c18g|Z3*l-jgeoml1{oh++Y75JI)RgU>LEY<%)C)X zI2rZ2kb>s^4cZuYeq3!A}DS`X~>Nd;+A$4e;ZwyD<1@2!8$ZKJ3w%!6)+sCALy+bKwyk zqKCS6qEGWmJ)97b-QXY|`<0lS5THkEtGgjE>ojOvuftfM&Ugd-rQg9C+|FdGM)HXs z(IxsA$&r(xg_j^4=hC;>s;1UF*Wp1I-2~sEF zZYgb?&`4bM1qjM*hR`yr3qJ(;L>Kj2XpBUy+)t((6z;bIr@-ihFNVAl4<#?{TWIaQ zIi>;YjXS_iIfNb?!N1t-!Y6vZvW5ZXE{%l7imzV9NvV4nf#G`Pcex;#@}?EINwsk7 z>UC=SlJC*b5a>-mgHP%q2+qF;cbNx ztCV@{s&fPsSt#;i@#G-m$as&$gLaG}ebOrtS5*22&glbhMH_fz8(~qVVN!VIVCKzg z1$U9^93(E%Ur9v_R*h#!t)Ce+#)+m(q^zCq%g&L-!E zC&et9WrT(49pl0S`?=DK7=`+;`CB!wP3ta97b)XdJ8K=@`DXOk0Q0};7zNT!`k4t@ z+)=9S)4p(jEGm5!qq)PDTmXiw3qDM19|fiylc@LtiQ=}Kfb#w&ckv^7tBj;cfwtY$q?IdliYlg zqh@4;IyW)OFPQPw4z|JsAEb7`+@yA@Q8SXQT#;upV`QNJ59Bg5m(jci3`0T4X-&^GU6)x7$Vi0XMWB(2hrdK^!hq0 zt!bDg$Hh)-9L62h`&{0PBf%7vM>69o`k4~kx^Wc)?lG!}=WgV2x-rq?HN#jMr^B0; p5zMeb2q5MEX5{g&Aa%N&e*pr!t%ZZ}>w*9P002ovPDHLkV1gpUS8xCT diff --git a/www/manual_lib/leaflet/dist/images/marker-shadow.png b/www/manual_lib/leaflet/dist/images/marker-shadow.png deleted file mode 100644 index d1e773c715a9b508ebea055c4bb4b0a2ad7f6e52..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 797 zcmV+&1LFLNP)oNwbRQ6Eq$4M3RDU@$ z<4cV9zWLV=bA&uX9wCpA{{f^4$D#k>GcX53-UQqf>_LzMU@frMz|MwbfQGbY0?ccG zBj_wh0?6Tv;HWR0`x;m^Bm<;sCm_85SGspFBn6|A!tDh$nR`wGorGkyL7j?F3#OJq zIswLIz;iF7f|LMnF(pXPAY*GYpsw%&e_WjlnV`C$6@#Q7GZu1$Q8>&p8=(iJj8o|T~0u%hM*Yg_d(Av{WS$h&pM%nlEAonVL0;DkN|xc zn)9F+aMDk#VtAMb0c=kIb1pU-$e4$3pwo&qVh(Umlw3_IU_dFcFe(In6*x}D4LHLhFZ4N=V2ZR+>XHU5D&uY$npJ7Eu?{iAK>UxC?4uyg4+iD z!nst**H%2zhOBxc7C7Tv{f^`%hqT1KpU@Vf6+C2|bGaR(1~TU5D-1;&HXT~PMc2Lu z{Q%^i6vvox&EMFT7I_)R$xq1779I8kE@?|D*cLWnP0a@a)xJA`o*^$^V(yN)b`kV7 z=o@jbFF4j{KeuQh - var sources = Array.prototype.slice.call(arguments, 1), - i, j, len, src; - - for (j = 0, len = sources.length; j < len; j++) { - src = sources[j] || {}; - for (i in src) { - if (src.hasOwnProperty(i)) { - dest[i] = src[i]; - } - } - } - return dest; - }, - - bind: function (fn, obj) { // (Function, Object) -> Function - var args = arguments.length > 2 ? Array.prototype.slice.call(arguments, 2) : null; - return function () { - return fn.apply(obj, args || arguments); - }; - }, - - stamp: (function () { - var lastId = 0, - key = '_leaflet_id'; - return function (obj) { - obj[key] = obj[key] || ++lastId; - return obj[key]; - }; - }()), - - invokeEach: function (obj, method, context) { - var i, args; - - if (typeof obj === 'object') { - args = Array.prototype.slice.call(arguments, 3); - - for (i in obj) { - method.apply(context, [i, obj[i]].concat(args)); - } - return true; - } - - return false; - }, - - limitExecByInterval: function (fn, time, context) { - var lock, execOnUnlock; - - return function wrapperFn() { - var args = arguments; - - if (lock) { - execOnUnlock = true; - return; - } - - lock = true; - - setTimeout(function () { - lock = false; - - if (execOnUnlock) { - wrapperFn.apply(context, args); - execOnUnlock = false; - } - }, time); - - fn.apply(context, args); - }; - }, - - falseFn: function () { - return false; - }, - - formatNum: function (num, digits) { - var pow = Math.pow(10, digits || 5); - return Math.round(num * pow) / pow; - }, - - trim: function (str) { - return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, ''); - }, - - splitWords: function (str) { - return L.Util.trim(str).split(/\s+/); - }, - - setOptions: function (obj, options) { - obj.options = L.extend({}, obj.options, options); - return obj.options; - }, - - getParamString: function (obj, existingUrl, uppercase) { - var params = []; - for (var i in obj) { - params.push(encodeURIComponent(uppercase ? i.toUpperCase() : i) + '=' + encodeURIComponent(obj[i])); - } - return ((!existingUrl || existingUrl.indexOf('?') === -1) ? '?' : '&') + params.join('&'); - }, - template: function (str, data) { - return str.replace(/\{ *([\w_]+) *\}/g, function (str, key) { - var value = data[key]; - if (value === undefined) { - throw new Error('No value provided for variable ' + str); - } else if (typeof value === 'function') { - value = value(data); - } - return value; - }); - }, - - isArray: Array.isArray || function (obj) { - return (Object.prototype.toString.call(obj) === '[object Array]'); - }, - - emptyImageUrl: 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=' -}; - -(function () { - - // inspired by http://paulirish.com/2011/requestanimationframe-for-smart-animating/ - - function getPrefixed(name) { - var i, fn, - prefixes = ['webkit', 'moz', 'o', 'ms']; - - for (i = 0; i < prefixes.length && !fn; i++) { - fn = window[prefixes[i] + name]; - } - - return fn; - } - - var lastTime = 0; - - function timeoutDefer(fn) { - var time = +new Date(), - timeToCall = Math.max(0, 16 - (time - lastTime)); - - lastTime = time + timeToCall; - return window.setTimeout(fn, timeToCall); - } - - var requestFn = window.requestAnimationFrame || - getPrefixed('RequestAnimationFrame') || timeoutDefer; - - var cancelFn = window.cancelAnimationFrame || - getPrefixed('CancelAnimationFrame') || - getPrefixed('CancelRequestAnimationFrame') || - function (id) { window.clearTimeout(id); }; - - - L.Util.requestAnimFrame = function (fn, context, immediate, element) { - fn = L.bind(fn, context); - - if (immediate && requestFn === timeoutDefer) { - fn(); - } else { - return requestFn.call(window, fn, element); - } - }; - - L.Util.cancelAnimFrame = function (id) { - if (id) { - cancelFn.call(window, id); - } - }; - -}()); - -// shortcuts for most used utility functions -L.extend = L.Util.extend; -L.bind = L.Util.bind; -L.stamp = L.Util.stamp; -L.setOptions = L.Util.setOptions; - - -/* - * L.Class powers the OOP facilities of the library. - * Thanks to John Resig and Dean Edwards for inspiration! - */ - -L.Class = function () {}; - -L.Class.extend = function (props) { - - // extended class with the new prototype - var NewClass = function () { - - // call the constructor - if (this.initialize) { - this.initialize.apply(this, arguments); - } - - // call all constructor hooks - if (this._initHooks) { - this.callInitHooks(); - } - }; - - // instantiate class without calling constructor - var F = function () {}; - F.prototype = this.prototype; - - var proto = new F(); - proto.constructor = NewClass; - - NewClass.prototype = proto; - - //inherit parent's statics - for (var i in this) { - if (this.hasOwnProperty(i) && i !== 'prototype') { - NewClass[i] = this[i]; - } - } - - // mix static properties into the class - if (props.statics) { - L.extend(NewClass, props.statics); - delete props.statics; - } - - // mix includes into the prototype - if (props.includes) { - L.Util.extend.apply(null, [proto].concat(props.includes)); - delete props.includes; - } - - // merge options - if (props.options && proto.options) { - props.options = L.extend({}, proto.options, props.options); - } - - // mix given properties into the prototype - L.extend(proto, props); - - proto._initHooks = []; - - var parent = this; - // jshint camelcase: false - NewClass.__super__ = parent.prototype; - - // add method for calling all hooks - proto.callInitHooks = function () { - - if (this._initHooksCalled) { return; } - - if (parent.prototype.callInitHooks) { - parent.prototype.callInitHooks.call(this); - } - - this._initHooksCalled = true; - - for (var i = 0, len = proto._initHooks.length; i < len; i++) { - proto._initHooks[i].call(this); - } - }; - - return NewClass; -}; - - -// method for adding properties to prototype -L.Class.include = function (props) { - L.extend(this.prototype, props); -}; - -// merge new default options to the Class -L.Class.mergeOptions = function (options) { - L.extend(this.prototype.options, options); -}; - -// add a constructor hook -L.Class.addInitHook = function (fn) { // (Function) || (String, args...) - var args = Array.prototype.slice.call(arguments, 1); - - var init = typeof fn === 'function' ? fn : function () { - this[fn].apply(this, args); - }; - - this.prototype._initHooks = this.prototype._initHooks || []; - this.prototype._initHooks.push(init); -}; - - -/* - * L.Mixin.Events is used to add custom events functionality to Leaflet classes. - */ - -var eventsKey = '_leaflet_events'; - -L.Mixin = {}; - -L.Mixin.Events = { - - addEventListener: function (types, fn, context) { // (String, Function[, Object]) or (Object[, Object]) - - // types can be a map of types/handlers - if (L.Util.invokeEach(types, this.addEventListener, this, fn, context)) { return this; } - - var events = this[eventsKey] = this[eventsKey] || {}, - contextId = context && context !== this && L.stamp(context), - i, len, event, type, indexKey, indexLenKey, typeIndex; - - // types can be a string of space-separated words - types = L.Util.splitWords(types); - - for (i = 0, len = types.length; i < len; i++) { - event = { - action: fn, - context: context || this - }; - type = types[i]; - - if (contextId) { - // store listeners of a particular context in a separate hash (if it has an id) - // gives a major performance boost when removing thousands of map layers - - indexKey = type + '_idx'; - indexLenKey = indexKey + '_len'; - - typeIndex = events[indexKey] = events[indexKey] || {}; - - if (!typeIndex[contextId]) { - typeIndex[contextId] = []; - - // keep track of the number of keys in the index to quickly check if it's empty - events[indexLenKey] = (events[indexLenKey] || 0) + 1; - } - - typeIndex[contextId].push(event); - - - } else { - events[type] = events[type] || []; - events[type].push(event); - } - } - - return this; - }, - - hasEventListeners: function (type) { // (String) -> Boolean - var events = this[eventsKey]; - return !!events && ((type in events && events[type].length > 0) || - (type + '_idx' in events && events[type + '_idx_len'] > 0)); - }, - - removeEventListener: function (types, fn, context) { // ([String, Function, Object]) or (Object[, Object]) - - if (!this[eventsKey]) { - return this; - } - - if (!types) { - return this.clearAllEventListeners(); - } - - if (L.Util.invokeEach(types, this.removeEventListener, this, fn, context)) { return this; } - - var events = this[eventsKey], - contextId = context && context !== this && L.stamp(context), - i, len, type, listeners, j, indexKey, indexLenKey, typeIndex, removed; - - types = L.Util.splitWords(types); - - for (i = 0, len = types.length; i < len; i++) { - type = types[i]; - indexKey = type + '_idx'; - indexLenKey = indexKey + '_len'; - - typeIndex = events[indexKey]; - - if (!fn) { - // clear all listeners for a type if function isn't specified - delete events[type]; - delete events[indexKey]; - delete events[indexLenKey]; - - } else { - listeners = contextId && typeIndex ? typeIndex[contextId] : events[type]; - - if (listeners) { - for (j = listeners.length - 1; j >= 0; j--) { - if ((listeners[j].action === fn) && (!context || (listeners[j].context === context))) { - removed = listeners.splice(j, 1); - // set the old action to a no-op, because it is possible - // that the listener is being iterated over as part of a dispatch - removed[0].action = L.Util.falseFn; - } - } - - if (context && typeIndex && (listeners.length === 0)) { - delete typeIndex[contextId]; - events[indexLenKey]--; - } - } - } - } - - return this; - }, - - clearAllEventListeners: function () { - delete this[eventsKey]; - return this; - }, - - fireEvent: function (type, data) { // (String[, Object]) - if (!this.hasEventListeners(type)) { - return this; - } - - var event = L.Util.extend({}, data, { type: type, target: this }); - - var events = this[eventsKey], - listeners, i, len, typeIndex, contextId; - - if (events[type]) { - // make sure adding/removing listeners inside other listeners won't cause infinite loop - listeners = events[type].slice(); - - for (i = 0, len = listeners.length; i < len; i++) { - listeners[i].action.call(listeners[i].context, event); - } - } - - // fire event for the context-indexed listeners as well - typeIndex = events[type + '_idx']; - - for (contextId in typeIndex) { - listeners = typeIndex[contextId].slice(); - - if (listeners) { - for (i = 0, len = listeners.length; i < len; i++) { - listeners[i].action.call(listeners[i].context, event); - } - } - } - - return this; - }, - - addOneTimeEventListener: function (types, fn, context) { - - if (L.Util.invokeEach(types, this.addOneTimeEventListener, this, fn, context)) { return this; } - - var handler = L.bind(function () { - this - .removeEventListener(types, fn, context) - .removeEventListener(types, handler, context); - }, this); - - return this - .addEventListener(types, fn, context) - .addEventListener(types, handler, context); - } -}; - -L.Mixin.Events.on = L.Mixin.Events.addEventListener; -L.Mixin.Events.off = L.Mixin.Events.removeEventListener; -L.Mixin.Events.once = L.Mixin.Events.addOneTimeEventListener; -L.Mixin.Events.fire = L.Mixin.Events.fireEvent; - - -/* - * L.Browser handles different browser and feature detections for internal Leaflet use. - */ - -(function () { - - var ie = 'ActiveXObject' in window, - ielt9 = ie && !document.addEventListener, - - // terrible browser detection to work around Safari / iOS / Android browser bugs - ua = navigator.userAgent.toLowerCase(), - webkit = ua.indexOf('webkit') !== -1, - chrome = ua.indexOf('chrome') !== -1, - phantomjs = ua.indexOf('phantom') !== -1, - android = ua.indexOf('android') !== -1, - android23 = ua.search('android [23]') !== -1, - gecko = ua.indexOf('gecko') !== -1, - - mobile = typeof orientation !== undefined + '', - msPointer = !window.PointerEvent && window.MSPointerEvent, - pointer = (window.PointerEvent && window.navigator.pointerEnabled) || - msPointer, - retina = ('devicePixelRatio' in window && window.devicePixelRatio > 1) || - ('matchMedia' in window && window.matchMedia('(min-resolution:144dpi)') && - window.matchMedia('(min-resolution:144dpi)').matches), - - doc = document.documentElement, - ie3d = ie && ('transition' in doc.style), - webkit3d = ('WebKitCSSMatrix' in window) && ('m11' in new window.WebKitCSSMatrix()) && !android23, - gecko3d = 'MozPerspective' in doc.style, - opera3d = 'OTransition' in doc.style, - any3d = !window.L_DISABLE_3D && (ie3d || webkit3d || gecko3d || opera3d) && !phantomjs; - - var touch = !window.L_NO_TOUCH && !phantomjs && (pointer || 'ontouchstart' in window || - (window.DocumentTouch && document instanceof window.DocumentTouch)); - - L.Browser = { - ie: ie, - ielt9: ielt9, - webkit: webkit, - gecko: gecko && !webkit && !window.opera && !ie, - - android: android, - android23: android23, - - chrome: chrome, - - ie3d: ie3d, - webkit3d: webkit3d, - gecko3d: gecko3d, - opera3d: opera3d, - any3d: any3d, - - mobile: mobile, - mobileWebkit: mobile && webkit, - mobileWebkit3d: mobile && webkit3d, - mobileOpera: mobile && window.opera, - - touch: touch, - msPointer: msPointer, - pointer: pointer, - - retina: retina - }; - -}()); - - -/* - * L.Point represents a point with x and y coordinates. - */ - -L.Point = function (/*Number*/ x, /*Number*/ y, /*Boolean*/ round) { - this.x = (round ? Math.round(x) : x); - this.y = (round ? Math.round(y) : y); -}; - -L.Point.prototype = { - - clone: function () { - return new L.Point(this.x, this.y); - }, - - // non-destructive, returns a new point - add: function (point) { - return this.clone()._add(L.point(point)); - }, - - // destructive, used directly for performance in situations where it's safe to modify existing point - _add: function (point) { - this.x += point.x; - this.y += point.y; - return this; - }, - - subtract: function (point) { - return this.clone()._subtract(L.point(point)); - }, - - _subtract: function (point) { - this.x -= point.x; - this.y -= point.y; - return this; - }, - - divideBy: function (num) { - return this.clone()._divideBy(num); - }, - - _divideBy: function (num) { - this.x /= num; - this.y /= num; - return this; - }, - - multiplyBy: function (num) { - return this.clone()._multiplyBy(num); - }, - - _multiplyBy: function (num) { - this.x *= num; - this.y *= num; - return this; - }, - - round: function () { - return this.clone()._round(); - }, - - _round: function () { - this.x = Math.round(this.x); - this.y = Math.round(this.y); - return this; - }, - - floor: function () { - return this.clone()._floor(); - }, - - _floor: function () { - this.x = Math.floor(this.x); - this.y = Math.floor(this.y); - return this; - }, - - distanceTo: function (point) { - point = L.point(point); - - var x = point.x - this.x, - y = point.y - this.y; - - return Math.sqrt(x * x + y * y); - }, - - equals: function (point) { - point = L.point(point); - - return point.x === this.x && - point.y === this.y; - }, - - contains: function (point) { - point = L.point(point); - - return Math.abs(point.x) <= Math.abs(this.x) && - Math.abs(point.y) <= Math.abs(this.y); - }, - - toString: function () { - return 'Point(' + - L.Util.formatNum(this.x) + ', ' + - L.Util.formatNum(this.y) + ')'; - } -}; - -L.point = function (x, y, round) { - if (x instanceof L.Point) { - return x; - } - if (L.Util.isArray(x)) { - return new L.Point(x[0], x[1]); - } - if (x === undefined || x === null) { - return x; - } - return new L.Point(x, y, round); -}; - - -/* - * L.Bounds represents a rectangular area on the screen in pixel coordinates. - */ - -L.Bounds = function (a, b) { //(Point, Point) or Point[] - if (!a) { return; } - - var points = b ? [a, b] : a; - - for (var i = 0, len = points.length; i < len; i++) { - this.extend(points[i]); - } -}; - -L.Bounds.prototype = { - // extend the bounds to contain the given point - extend: function (point) { // (Point) - point = L.point(point); - - if (!this.min && !this.max) { - this.min = point.clone(); - this.max = point.clone(); - } else { - this.min.x = Math.min(point.x, this.min.x); - this.max.x = Math.max(point.x, this.max.x); - this.min.y = Math.min(point.y, this.min.y); - this.max.y = Math.max(point.y, this.max.y); - } - return this; - }, - - getCenter: function (round) { // (Boolean) -> Point - return new L.Point( - (this.min.x + this.max.x) / 2, - (this.min.y + this.max.y) / 2, round); - }, - - getBottomLeft: function () { // -> Point - return new L.Point(this.min.x, this.max.y); - }, - - getTopRight: function () { // -> Point - return new L.Point(this.max.x, this.min.y); - }, - - getSize: function () { - return this.max.subtract(this.min); - }, - - contains: function (obj) { // (Bounds) or (Point) -> Boolean - var min, max; - - if (typeof obj[0] === 'number' || obj instanceof L.Point) { - obj = L.point(obj); - } else { - obj = L.bounds(obj); - } - - if (obj instanceof L.Bounds) { - min = obj.min; - max = obj.max; - } else { - min = max = obj; - } - - return (min.x >= this.min.x) && - (max.x <= this.max.x) && - (min.y >= this.min.y) && - (max.y <= this.max.y); - }, - - intersects: function (bounds) { // (Bounds) -> Boolean - bounds = L.bounds(bounds); - - var min = this.min, - max = this.max, - min2 = bounds.min, - max2 = bounds.max, - xIntersects = (max2.x >= min.x) && (min2.x <= max.x), - yIntersects = (max2.y >= min.y) && (min2.y <= max.y); - - return xIntersects && yIntersects; - }, - - isValid: function () { - return !!(this.min && this.max); - } -}; - -L.bounds = function (a, b) { // (Bounds) or (Point, Point) or (Point[]) - if (!a || a instanceof L.Bounds) { - return a; - } - return new L.Bounds(a, b); -}; - - -/* - * L.Transformation is an utility class to perform simple point transformations through a 2d-matrix. - */ - -L.Transformation = function (a, b, c, d) { - this._a = a; - this._b = b; - this._c = c; - this._d = d; -}; - -L.Transformation.prototype = { - transform: function (point, scale) { // (Point, Number) -> Point - return this._transform(point.clone(), scale); - }, - - // destructive transform (faster) - _transform: function (point, scale) { - scale = scale || 1; - point.x = scale * (this._a * point.x + this._b); - point.y = scale * (this._c * point.y + this._d); - return point; - }, - - untransform: function (point, scale) { - scale = scale || 1; - return new L.Point( - (point.x / scale - this._b) / this._a, - (point.y / scale - this._d) / this._c); - } -}; - - -/* - * L.DomUtil contains various utility functions for working with DOM. - */ - -L.DomUtil = { - get: function (id) { - return (typeof id === 'string' ? document.getElementById(id) : id); - }, - - getStyle: function (el, style) { - - var value = el.style[style]; - - if (!value && el.currentStyle) { - value = el.currentStyle[style]; - } - - if ((!value || value === 'auto') && document.defaultView) { - var css = document.defaultView.getComputedStyle(el, null); - value = css ? css[style] : null; - } - - return value === 'auto' ? null : value; - }, - - getViewportOffset: function (element) { - - var top = 0, - left = 0, - el = element, - docBody = document.body, - docEl = document.documentElement, - pos; - - do { - top += el.offsetTop || 0; - left += el.offsetLeft || 0; - - //add borders - top += parseInt(L.DomUtil.getStyle(el, 'borderTopWidth'), 10) || 0; - left += parseInt(L.DomUtil.getStyle(el, 'borderLeftWidth'), 10) || 0; - - pos = L.DomUtil.getStyle(el, 'position'); - - if (el.offsetParent === docBody && pos === 'absolute') { break; } - - if (pos === 'fixed') { - top += docBody.scrollTop || docEl.scrollTop || 0; - left += docBody.scrollLeft || docEl.scrollLeft || 0; - break; - } - - if (pos === 'relative' && !el.offsetLeft) { - var width = L.DomUtil.getStyle(el, 'width'), - maxWidth = L.DomUtil.getStyle(el, 'max-width'), - r = el.getBoundingClientRect(); - - if (width !== 'none' || maxWidth !== 'none') { - left += r.left + el.clientLeft; - } - - //calculate full y offset since we're breaking out of the loop - top += r.top + (docBody.scrollTop || docEl.scrollTop || 0); - - break; - } - - el = el.offsetParent; - - } while (el); - - el = element; - - do { - if (el === docBody) { break; } - - top -= el.scrollTop || 0; - left -= el.scrollLeft || 0; - - el = el.parentNode; - } while (el); - - return new L.Point(left, top); - }, - - documentIsLtr: function () { - if (!L.DomUtil._docIsLtrCached) { - L.DomUtil._docIsLtrCached = true; - L.DomUtil._docIsLtr = L.DomUtil.getStyle(document.body, 'direction') === 'ltr'; - } - return L.DomUtil._docIsLtr; - }, - - create: function (tagName, className, container) { - - var el = document.createElement(tagName); - el.className = className; - - if (container) { - container.appendChild(el); - } - - return el; - }, - - hasClass: function (el, name) { - if (el.classList !== undefined) { - return el.classList.contains(name); - } - var className = L.DomUtil._getClass(el); - return className.length > 0 && new RegExp('(^|\\s)' + name + '(\\s|$)').test(className); - }, - - addClass: function (el, name) { - if (el.classList !== undefined) { - var classes = L.Util.splitWords(name); - for (var i = 0, len = classes.length; i < len; i++) { - el.classList.add(classes[i]); - } - } else if (!L.DomUtil.hasClass(el, name)) { - var className = L.DomUtil._getClass(el); - L.DomUtil._setClass(el, (className ? className + ' ' : '') + name); - } - }, - - removeClass: function (el, name) { - if (el.classList !== undefined) { - el.classList.remove(name); - } else { - L.DomUtil._setClass(el, L.Util.trim((' ' + L.DomUtil._getClass(el) + ' ').replace(' ' + name + ' ', ' '))); - } - }, - - _setClass: function (el, name) { - if (el.className.baseVal === undefined) { - el.className = name; - } else { - // in case of SVG element - el.className.baseVal = name; - } - }, - - _getClass: function (el) { - return el.className.baseVal === undefined ? el.className : el.className.baseVal; - }, - - setOpacity: function (el, value) { - - if ('opacity' in el.style) { - el.style.opacity = value; - - } else if ('filter' in el.style) { - - var filter = false, - filterName = 'DXImageTransform.Microsoft.Alpha'; - - // filters collection throws an error if we try to retrieve a filter that doesn't exist - try { - filter = el.filters.item(filterName); - } catch (e) { - // don't set opacity to 1 if we haven't already set an opacity, - // it isn't needed and breaks transparent pngs. - if (value === 1) { return; } - } - - value = Math.round(value * 100); - - if (filter) { - filter.Enabled = (value !== 100); - filter.Opacity = value; - } else { - el.style.filter += ' progid:' + filterName + '(opacity=' + value + ')'; - } - } - }, - - testProp: function (props) { - - var style = document.documentElement.style; - - for (var i = 0; i < props.length; i++) { - if (props[i] in style) { - return props[i]; - } - } - return false; - }, - - getTranslateString: function (point) { - // on WebKit browsers (Chrome/Safari/iOS Safari/Android) using translate3d instead of translate - // makes animation smoother as it ensures HW accel is used. Firefox 13 doesn't care - // (same speed either way), Opera 12 doesn't support translate3d - - var is3d = L.Browser.webkit3d, - open = 'translate' + (is3d ? '3d' : '') + '(', - close = (is3d ? ',0' : '') + ')'; - - return open + point.x + 'px,' + point.y + 'px' + close; - }, - - getScaleString: function (scale, origin) { - - var preTranslateStr = L.DomUtil.getTranslateString(origin.add(origin.multiplyBy(-1 * scale))), - scaleStr = ' scale(' + scale + ') '; - - return preTranslateStr + scaleStr; - }, - - setPosition: function (el, point, disable3D) { // (HTMLElement, Point[, Boolean]) - - // jshint camelcase: false - el._leaflet_pos = point; - - if (!disable3D && L.Browser.any3d) { - el.style[L.DomUtil.TRANSFORM] = L.DomUtil.getTranslateString(point); - } else { - el.style.left = point.x + 'px'; - el.style.top = point.y + 'px'; - } - }, - - getPosition: function (el) { - // this method is only used for elements previously positioned using setPosition, - // so it's safe to cache the position for performance - - // jshint camelcase: false - return el._leaflet_pos; - } -}; - - -// prefix style property names - -L.DomUtil.TRANSFORM = L.DomUtil.testProp( - ['transform', 'WebkitTransform', 'OTransform', 'MozTransform', 'msTransform']); - -// webkitTransition comes first because some browser versions that drop vendor prefix don't do -// the same for the transitionend event, in particular the Android 4.1 stock browser - -L.DomUtil.TRANSITION = L.DomUtil.testProp( - ['webkitTransition', 'transition', 'OTransition', 'MozTransition', 'msTransition']); - -L.DomUtil.TRANSITION_END = - L.DomUtil.TRANSITION === 'webkitTransition' || L.DomUtil.TRANSITION === 'OTransition' ? - L.DomUtil.TRANSITION + 'End' : 'transitionend'; - -(function () { - if ('onselectstart' in document) { - L.extend(L.DomUtil, { - disableTextSelection: function () { - L.DomEvent.on(window, 'selectstart', L.DomEvent.preventDefault); - }, - - enableTextSelection: function () { - L.DomEvent.off(window, 'selectstart', L.DomEvent.preventDefault); - } - }); - } else { - var userSelectProperty = L.DomUtil.testProp( - ['userSelect', 'WebkitUserSelect', 'OUserSelect', 'MozUserSelect', 'msUserSelect']); - - L.extend(L.DomUtil, { - disableTextSelection: function () { - if (userSelectProperty) { - var style = document.documentElement.style; - this._userSelect = style[userSelectProperty]; - style[userSelectProperty] = 'none'; - } - }, - - enableTextSelection: function () { - if (userSelectProperty) { - document.documentElement.style[userSelectProperty] = this._userSelect; - delete this._userSelect; - } - } - }); - } - - L.extend(L.DomUtil, { - disableImageDrag: function () { - L.DomEvent.on(window, 'dragstart', L.DomEvent.preventDefault); - }, - - enableImageDrag: function () { - L.DomEvent.off(window, 'dragstart', L.DomEvent.preventDefault); - } - }); -})(); - - -/* - * L.LatLng represents a geographical point with latitude and longitude coordinates. - */ - -L.LatLng = function (lat, lng, alt) { // (Number, Number, Number) - lat = parseFloat(lat); - lng = parseFloat(lng); - - if (isNaN(lat) || isNaN(lng)) { - throw new Error('Invalid LatLng object: (' + lat + ', ' + lng + ')'); - } - - this.lat = lat; - this.lng = lng; - - if (alt !== undefined) { - this.alt = parseFloat(alt); - } -}; - -L.extend(L.LatLng, { - DEG_TO_RAD: Math.PI / 180, - RAD_TO_DEG: 180 / Math.PI, - MAX_MARGIN: 1.0E-9 // max margin of error for the "equals" check -}); - -L.LatLng.prototype = { - equals: function (obj) { // (LatLng) -> Boolean - if (!obj) { return false; } - - obj = L.latLng(obj); - - var margin = Math.max( - Math.abs(this.lat - obj.lat), - Math.abs(this.lng - obj.lng)); - - return margin <= L.LatLng.MAX_MARGIN; - }, - - toString: function (precision) { // (Number) -> String - return 'LatLng(' + - L.Util.formatNum(this.lat, precision) + ', ' + - L.Util.formatNum(this.lng, precision) + ')'; - }, - - // Haversine distance formula, see http://en.wikipedia.org/wiki/Haversine_formula - // TODO move to projection code, LatLng shouldn't know about Earth - distanceTo: function (other) { // (LatLng) -> Number - other = L.latLng(other); - - var R = 6378137, // earth radius in meters - d2r = L.LatLng.DEG_TO_RAD, - dLat = (other.lat - this.lat) * d2r, - dLon = (other.lng - this.lng) * d2r, - lat1 = this.lat * d2r, - lat2 = other.lat * d2r, - sin1 = Math.sin(dLat / 2), - sin2 = Math.sin(dLon / 2); - - var a = sin1 * sin1 + sin2 * sin2 * Math.cos(lat1) * Math.cos(lat2); - - return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); - }, - - wrap: function (a, b) { // (Number, Number) -> LatLng - var lng = this.lng; - - a = a || -180; - b = b || 180; - - lng = (lng + b) % (b - a) + (lng < a || lng === b ? b : a); - - return new L.LatLng(this.lat, lng); - } -}; - -L.latLng = function (a, b) { // (LatLng) or ([Number, Number]) or (Number, Number) - if (a instanceof L.LatLng) { - return a; - } - if (L.Util.isArray(a)) { - if (typeof a[0] === 'number' || typeof a[0] === 'string') { - return new L.LatLng(a[0], a[1], a[2]); - } else { - return null; - } - } - if (a === undefined || a === null) { - return a; - } - if (typeof a === 'object' && 'lat' in a) { - return new L.LatLng(a.lat, 'lng' in a ? a.lng : a.lon); - } - if (b === undefined) { - return null; - } - return new L.LatLng(a, b); -}; - - - -/* - * L.LatLngBounds represents a rectangular area on the map in geographical coordinates. - */ - -L.LatLngBounds = function (southWest, northEast) { // (LatLng, LatLng) or (LatLng[]) - if (!southWest) { return; } - - var latlngs = northEast ? [southWest, northEast] : southWest; - - for (var i = 0, len = latlngs.length; i < len; i++) { - this.extend(latlngs[i]); - } -}; - -L.LatLngBounds.prototype = { - // extend the bounds to contain the given point or bounds - extend: function (obj) { // (LatLng) or (LatLngBounds) - if (!obj) { return this; } - - var latLng = L.latLng(obj); - if (latLng !== null) { - obj = latLng; - } else { - obj = L.latLngBounds(obj); - } - - if (obj instanceof L.LatLng) { - if (!this._southWest && !this._northEast) { - this._southWest = new L.LatLng(obj.lat, obj.lng); - this._northEast = new L.LatLng(obj.lat, obj.lng); - } else { - this._southWest.lat = Math.min(obj.lat, this._southWest.lat); - this._southWest.lng = Math.min(obj.lng, this._southWest.lng); - - this._northEast.lat = Math.max(obj.lat, this._northEast.lat); - this._northEast.lng = Math.max(obj.lng, this._northEast.lng); - } - } else if (obj instanceof L.LatLngBounds) { - this.extend(obj._southWest); - this.extend(obj._northEast); - } - return this; - }, - - // extend the bounds by a percentage - pad: function (bufferRatio) { // (Number) -> LatLngBounds - var sw = this._southWest, - ne = this._northEast, - heightBuffer = Math.abs(sw.lat - ne.lat) * bufferRatio, - widthBuffer = Math.abs(sw.lng - ne.lng) * bufferRatio; - - return new L.LatLngBounds( - new L.LatLng(sw.lat - heightBuffer, sw.lng - widthBuffer), - new L.LatLng(ne.lat + heightBuffer, ne.lng + widthBuffer)); - }, - - getCenter: function () { // -> LatLng - return new L.LatLng( - (this._southWest.lat + this._northEast.lat) / 2, - (this._southWest.lng + this._northEast.lng) / 2); - }, - - getSouthWest: function () { - return this._southWest; - }, - - getNorthEast: function () { - return this._northEast; - }, - - getNorthWest: function () { - return new L.LatLng(this.getNorth(), this.getWest()); - }, - - getSouthEast: function () { - return new L.LatLng(this.getSouth(), this.getEast()); - }, - - getWest: function () { - return this._southWest.lng; - }, - - getSouth: function () { - return this._southWest.lat; - }, - - getEast: function () { - return this._northEast.lng; - }, - - getNorth: function () { - return this._northEast.lat; - }, - - contains: function (obj) { // (LatLngBounds) or (LatLng) -> Boolean - if (typeof obj[0] === 'number' || obj instanceof L.LatLng) { - obj = L.latLng(obj); - } else { - obj = L.latLngBounds(obj); - } - - var sw = this._southWest, - ne = this._northEast, - sw2, ne2; - - if (obj instanceof L.LatLngBounds) { - sw2 = obj.getSouthWest(); - ne2 = obj.getNorthEast(); - } else { - sw2 = ne2 = obj; - } - - return (sw2.lat >= sw.lat) && (ne2.lat <= ne.lat) && - (sw2.lng >= sw.lng) && (ne2.lng <= ne.lng); - }, - - intersects: function (bounds) { // (LatLngBounds) - bounds = L.latLngBounds(bounds); - - var sw = this._southWest, - ne = this._northEast, - sw2 = bounds.getSouthWest(), - ne2 = bounds.getNorthEast(), - - latIntersects = (ne2.lat >= sw.lat) && (sw2.lat <= ne.lat), - lngIntersects = (ne2.lng >= sw.lng) && (sw2.lng <= ne.lng); - - return latIntersects && lngIntersects; - }, - - toBBoxString: function () { - return [this.getWest(), this.getSouth(), this.getEast(), this.getNorth()].join(','); - }, - - equals: function (bounds) { // (LatLngBounds) - if (!bounds) { return false; } - - bounds = L.latLngBounds(bounds); - - return this._southWest.equals(bounds.getSouthWest()) && - this._northEast.equals(bounds.getNorthEast()); - }, - - isValid: function () { - return !!(this._southWest && this._northEast); - } -}; - -//TODO International date line? - -L.latLngBounds = function (a, b) { // (LatLngBounds) or (LatLng, LatLng) - if (!a || a instanceof L.LatLngBounds) { - return a; - } - return new L.LatLngBounds(a, b); -}; - - -/* - * L.Projection contains various geographical projections used by CRS classes. - */ - -L.Projection = {}; - - -/* - * Spherical Mercator is the most popular map projection, used by EPSG:3857 CRS used by default. - */ - -L.Projection.SphericalMercator = { - MAX_LATITUDE: 85.0511287798, - - project: function (latlng) { // (LatLng) -> Point - var d = L.LatLng.DEG_TO_RAD, - max = this.MAX_LATITUDE, - lat = Math.max(Math.min(max, latlng.lat), -max), - x = latlng.lng * d, - y = lat * d; - - y = Math.log(Math.tan((Math.PI / 4) + (y / 2))); - - return new L.Point(x, y); - }, - - unproject: function (point) { // (Point, Boolean) -> LatLng - var d = L.LatLng.RAD_TO_DEG, - lng = point.x * d, - lat = (2 * Math.atan(Math.exp(point.y)) - (Math.PI / 2)) * d; - - return new L.LatLng(lat, lng); - } -}; - - -/* - * Simple equirectangular (Plate Carree) projection, used by CRS like EPSG:4326 and Simple. - */ - -L.Projection.LonLat = { - project: function (latlng) { - return new L.Point(latlng.lng, latlng.lat); - }, - - unproject: function (point) { - return new L.LatLng(point.y, point.x); - } -}; - - -/* - * L.CRS is a base object for all defined CRS (Coordinate Reference Systems) in Leaflet. - */ - -L.CRS = { - latLngToPoint: function (latlng, zoom) { // (LatLng, Number) -> Point - var projectedPoint = this.projection.project(latlng), - scale = this.scale(zoom); - - return this.transformation._transform(projectedPoint, scale); - }, - - pointToLatLng: function (point, zoom) { // (Point, Number[, Boolean]) -> LatLng - var scale = this.scale(zoom), - untransformedPoint = this.transformation.untransform(point, scale); - - return this.projection.unproject(untransformedPoint); - }, - - project: function (latlng) { - return this.projection.project(latlng); - }, - - scale: function (zoom) { - return 256 * Math.pow(2, zoom); - }, - - getSize: function (zoom) { - var s = this.scale(zoom); - return L.point(s, s); - } -}; - - -/* - * A simple CRS that can be used for flat non-Earth maps like panoramas or game maps. - */ - -L.CRS.Simple = L.extend({}, L.CRS, { - projection: L.Projection.LonLat, - transformation: new L.Transformation(1, 0, -1, 0), - - scale: function (zoom) { - return Math.pow(2, zoom); - } -}); - - -/* - * L.CRS.EPSG3857 (Spherical Mercator) is the most common CRS for web mapping - * and is used by Leaflet by default. - */ - -L.CRS.EPSG3857 = L.extend({}, L.CRS, { - code: 'EPSG:3857', - - projection: L.Projection.SphericalMercator, - transformation: new L.Transformation(0.5 / Math.PI, 0.5, -0.5 / Math.PI, 0.5), - - project: function (latlng) { // (LatLng) -> Point - var projectedPoint = this.projection.project(latlng), - earthRadius = 6378137; - return projectedPoint.multiplyBy(earthRadius); - } -}); - -L.CRS.EPSG900913 = L.extend({}, L.CRS.EPSG3857, { - code: 'EPSG:900913' -}); - - -/* - * L.CRS.EPSG4326 is a CRS popular among advanced GIS specialists. - */ - -L.CRS.EPSG4326 = L.extend({}, L.CRS, { - code: 'EPSG:4326', - - projection: L.Projection.LonLat, - transformation: new L.Transformation(1 / 360, 0.5, -1 / 360, 0.5) -}); - - -/* - * L.Map is the central class of the API - it is used to create a map. - */ - -L.Map = L.Class.extend({ - - includes: L.Mixin.Events, - - options: { - crs: L.CRS.EPSG3857, - - /* - center: LatLng, - zoom: Number, - layers: Array, - */ - - fadeAnimation: L.DomUtil.TRANSITION && !L.Browser.android23, - trackResize: true, - markerZoomAnimation: L.DomUtil.TRANSITION && L.Browser.any3d - }, - - initialize: function (id, options) { // (HTMLElement or String, Object) - options = L.setOptions(this, options); - - - this._initContainer(id); - this._initLayout(); - - // hack for https://github.com/Leaflet/Leaflet/issues/1980 - this._onResize = L.bind(this._onResize, this); - - this._initEvents(); - - if (options.maxBounds) { - this.setMaxBounds(options.maxBounds); - } - - if (options.center && options.zoom !== undefined) { - this.setView(L.latLng(options.center), options.zoom, {reset: true}); - } - - this._handlers = []; - - this._layers = {}; - this._zoomBoundLayers = {}; - this._tileLayersNum = 0; - - this.callInitHooks(); - - this._addLayers(options.layers); - }, - - - // public methods that modify map state - - // replaced by animation-powered implementation in Map.PanAnimation.js - setView: function (center, zoom) { - zoom = zoom === undefined ? this.getZoom() : zoom; - this._resetView(L.latLng(center), this._limitZoom(zoom)); - return this; - }, - - setZoom: function (zoom, options) { - if (!this._loaded) { - this._zoom = this._limitZoom(zoom); - return this; - } - return this.setView(this.getCenter(), zoom, {zoom: options}); - }, - - zoomIn: function (delta, options) { - return this.setZoom(this._zoom + (delta || 1), options); - }, - - zoomOut: function (delta, options) { - return this.setZoom(this._zoom - (delta || 1), options); - }, - - setZoomAround: function (latlng, zoom, options) { - var scale = this.getZoomScale(zoom), - viewHalf = this.getSize().divideBy(2), - containerPoint = latlng instanceof L.Point ? latlng : this.latLngToContainerPoint(latlng), - - centerOffset = containerPoint.subtract(viewHalf).multiplyBy(1 - 1 / scale), - newCenter = this.containerPointToLatLng(viewHalf.add(centerOffset)); - - return this.setView(newCenter, zoom, {zoom: options}); - }, - - fitBounds: function (bounds, options) { - - options = options || {}; - bounds = bounds.getBounds ? bounds.getBounds() : L.latLngBounds(bounds); - - var paddingTL = L.point(options.paddingTopLeft || options.padding || [0, 0]), - paddingBR = L.point(options.paddingBottomRight || options.padding || [0, 0]), - - zoom = this.getBoundsZoom(bounds, false, paddingTL.add(paddingBR)); - - zoom = (options.maxZoom) ? Math.min(options.maxZoom, zoom) : zoom; - - var paddingOffset = paddingBR.subtract(paddingTL).divideBy(2), - - swPoint = this.project(bounds.getSouthWest(), zoom), - nePoint = this.project(bounds.getNorthEast(), zoom), - center = this.unproject(swPoint.add(nePoint).divideBy(2).add(paddingOffset), zoom); - - return this.setView(center, zoom, options); - }, - - fitWorld: function (options) { - return this.fitBounds([[-90, -180], [90, 180]], options); - }, - - panTo: function (center, options) { // (LatLng) - return this.setView(center, this._zoom, {pan: options}); - }, - - panBy: function (offset) { // (Point) - // replaced with animated panBy in Map.PanAnimation.js - this.fire('movestart'); - - this._rawPanBy(L.point(offset)); - - this.fire('move'); - return this.fire('moveend'); - }, - - setMaxBounds: function (bounds) { - bounds = L.latLngBounds(bounds); - - this.options.maxBounds = bounds; - - if (!bounds) { - return this.off('moveend', this._panInsideMaxBounds, this); - } - - if (this._loaded) { - this._panInsideMaxBounds(); - } - - return this.on('moveend', this._panInsideMaxBounds, this); - }, - - panInsideBounds: function (bounds, options) { - var center = this.getCenter(), - newCenter = this._limitCenter(center, this._zoom, bounds); - - if (center.equals(newCenter)) { return this; } - - return this.panTo(newCenter, options); - }, - - addLayer: function (layer) { - // TODO method is too big, refactor - - var id = L.stamp(layer); - - if (this._layers[id]) { return this; } - - this._layers[id] = layer; - - // TODO getMaxZoom, getMinZoom in ILayer (instead of options) - if (layer.options && (!isNaN(layer.options.maxZoom) || !isNaN(layer.options.minZoom))) { - this._zoomBoundLayers[id] = layer; - this._updateZoomLevels(); - } - - // TODO looks ugly, refactor!!! - if (this.options.zoomAnimation && L.TileLayer && (layer instanceof L.TileLayer)) { - this._tileLayersNum++; - this._tileLayersToLoad++; - layer.on('load', this._onTileLayerLoad, this); - } - - if (this._loaded) { - this._layerAdd(layer); - } - - return this; - }, - - removeLayer: function (layer) { - var id = L.stamp(layer); - - if (!this._layers[id]) { return this; } - - if (this._loaded) { - layer.onRemove(this); - } - - delete this._layers[id]; - - if (this._loaded) { - this.fire('layerremove', {layer: layer}); - } - - if (this._zoomBoundLayers[id]) { - delete this._zoomBoundLayers[id]; - this._updateZoomLevels(); - } - - // TODO looks ugly, refactor - if (this.options.zoomAnimation && L.TileLayer && (layer instanceof L.TileLayer)) { - this._tileLayersNum--; - this._tileLayersToLoad--; - layer.off('load', this._onTileLayerLoad, this); - } - - return this; - }, - - hasLayer: function (layer) { - if (!layer) { return false; } - - return (L.stamp(layer) in this._layers); - }, - - eachLayer: function (method, context) { - for (var i in this._layers) { - method.call(context, this._layers[i]); - } - return this; - }, - - invalidateSize: function (options) { - if (!this._loaded) { return this; } - - options = L.extend({ - animate: false, - pan: true - }, options === true ? {animate: true} : options); - - var oldSize = this.getSize(); - this._sizeChanged = true; - this._initialCenter = null; - - var newSize = this.getSize(), - oldCenter = oldSize.divideBy(2).round(), - newCenter = newSize.divideBy(2).round(), - offset = oldCenter.subtract(newCenter); - - if (!offset.x && !offset.y) { return this; } - - if (options.animate && options.pan) { - this.panBy(offset); - - } else { - if (options.pan) { - this._rawPanBy(offset); - } - - this.fire('move'); - - if (options.debounceMoveend) { - clearTimeout(this._sizeTimer); - this._sizeTimer = setTimeout(L.bind(this.fire, this, 'moveend'), 200); - } else { - this.fire('moveend'); - } - } - - return this.fire('resize', { - oldSize: oldSize, - newSize: newSize - }); - }, - - // TODO handler.addTo - addHandler: function (name, HandlerClass) { - if (!HandlerClass) { return this; } - - var handler = this[name] = new HandlerClass(this); - - this._handlers.push(handler); - - if (this.options[name]) { - handler.enable(); - } - - return this; - }, - - remove: function () { - if (this._loaded) { - this.fire('unload'); - } - - this._initEvents('off'); - - try { - // throws error in IE6-8 - delete this._container._leaflet; - } catch (e) { - this._container._leaflet = undefined; - } - - this._clearPanes(); - if (this._clearControlPos) { - this._clearControlPos(); - } - - this._clearHandlers(); - - return this; - }, - - - // public methods for getting map state - - getCenter: function () { // (Boolean) -> LatLng - this._checkIfLoaded(); - - if (this._initialCenter && !this._moved()) { - return this._initialCenter; - } - return this.layerPointToLatLng(this._getCenterLayerPoint()); - }, - - getZoom: function () { - return this._zoom; - }, - - getBounds: function () { - var bounds = this.getPixelBounds(), - sw = this.unproject(bounds.getBottomLeft()), - ne = this.unproject(bounds.getTopRight()); - - return new L.LatLngBounds(sw, ne); - }, - - getMinZoom: function () { - return this.options.minZoom === undefined ? - (this._layersMinZoom === undefined ? 0 : this._layersMinZoom) : - this.options.minZoom; - }, - - getMaxZoom: function () { - return this.options.maxZoom === undefined ? - (this._layersMaxZoom === undefined ? Infinity : this._layersMaxZoom) : - this.options.maxZoom; - }, - - getBoundsZoom: function (bounds, inside, padding) { // (LatLngBounds[, Boolean, Point]) -> Number - bounds = L.latLngBounds(bounds); - - var zoom = this.getMinZoom() - (inside ? 1 : 0), - maxZoom = this.getMaxZoom(), - size = this.getSize(), - - nw = bounds.getNorthWest(), - se = bounds.getSouthEast(), - - zoomNotFound = true, - boundsSize; - - padding = L.point(padding || [0, 0]); - - do { - zoom++; - boundsSize = this.project(se, zoom).subtract(this.project(nw, zoom)).add(padding); - zoomNotFound = !inside ? size.contains(boundsSize) : boundsSize.x < size.x || boundsSize.y < size.y; - - } while (zoomNotFound && zoom <= maxZoom); - - if (zoomNotFound && inside) { - return null; - } - - return inside ? zoom : zoom - 1; - }, - - getSize: function () { - if (!this._size || this._sizeChanged) { - this._size = new L.Point( - this._container.clientWidth, - this._container.clientHeight); - - this._sizeChanged = false; - } - return this._size.clone(); - }, - - getPixelBounds: function () { - var topLeftPoint = this._getTopLeftPoint(); - return new L.Bounds(topLeftPoint, topLeftPoint.add(this.getSize())); - }, - - getPixelOrigin: function () { - this._checkIfLoaded(); - return this._initialTopLeftPoint; - }, - - getPanes: function () { - return this._panes; - }, - - getContainer: function () { - return this._container; - }, - - - // TODO replace with universal implementation after refactoring projections - - getZoomScale: function (toZoom) { - var crs = this.options.crs; - return crs.scale(toZoom) / crs.scale(this._zoom); - }, - - getScaleZoom: function (scale) { - return this._zoom + (Math.log(scale) / Math.LN2); - }, - - - // conversion methods - - project: function (latlng, zoom) { // (LatLng[, Number]) -> Point - zoom = zoom === undefined ? this._zoom : zoom; - return this.options.crs.latLngToPoint(L.latLng(latlng), zoom); - }, - - unproject: function (point, zoom) { // (Point[, Number]) -> LatLng - zoom = zoom === undefined ? this._zoom : zoom; - return this.options.crs.pointToLatLng(L.point(point), zoom); - }, - - layerPointToLatLng: function (point) { // (Point) - var projectedPoint = L.point(point).add(this.getPixelOrigin()); - return this.unproject(projectedPoint); - }, - - latLngToLayerPoint: function (latlng) { // (LatLng) - var projectedPoint = this.project(L.latLng(latlng))._round(); - return projectedPoint._subtract(this.getPixelOrigin()); - }, - - containerPointToLayerPoint: function (point) { // (Point) - return L.point(point).subtract(this._getMapPanePos()); - }, - - layerPointToContainerPoint: function (point) { // (Point) - return L.point(point).add(this._getMapPanePos()); - }, - - containerPointToLatLng: function (point) { - var layerPoint = this.containerPointToLayerPoint(L.point(point)); - return this.layerPointToLatLng(layerPoint); - }, - - latLngToContainerPoint: function (latlng) { - return this.layerPointToContainerPoint(this.latLngToLayerPoint(L.latLng(latlng))); - }, - - mouseEventToContainerPoint: function (e) { // (MouseEvent) - return L.DomEvent.getMousePosition(e, this._container); - }, - - mouseEventToLayerPoint: function (e) { // (MouseEvent) - return this.containerPointToLayerPoint(this.mouseEventToContainerPoint(e)); - }, - - mouseEventToLatLng: function (e) { // (MouseEvent) - return this.layerPointToLatLng(this.mouseEventToLayerPoint(e)); - }, - - - // map initialization methods - - _initContainer: function (id) { - var container = this._container = L.DomUtil.get(id); - - if (!container) { - throw new Error('Map container not found.'); - } else if (container._leaflet) { - throw new Error('Map container is already initialized.'); - } - - container._leaflet = true; - }, - - _initLayout: function () { - var container = this._container; - - L.DomUtil.addClass(container, 'leaflet-container' + - (L.Browser.touch ? ' leaflet-touch' : '') + - (L.Browser.retina ? ' leaflet-retina' : '') + - (L.Browser.ielt9 ? ' leaflet-oldie' : '') + - (this.options.fadeAnimation ? ' leaflet-fade-anim' : '')); - - var position = L.DomUtil.getStyle(container, 'position'); - - if (position !== 'absolute' && position !== 'relative' && position !== 'fixed') { - container.style.position = 'relative'; - } - - this._initPanes(); - - if (this._initControlPos) { - this._initControlPos(); - } - }, - - _initPanes: function () { - var panes = this._panes = {}; - - this._mapPane = panes.mapPane = this._createPane('leaflet-map-pane', this._container); - - this._tilePane = panes.tilePane = this._createPane('leaflet-tile-pane', this._mapPane); - panes.objectsPane = this._createPane('leaflet-objects-pane', this._mapPane); - panes.shadowPane = this._createPane('leaflet-shadow-pane'); - panes.overlayPane = this._createPane('leaflet-overlay-pane'); - panes.markerPane = this._createPane('leaflet-marker-pane'); - panes.popupPane = this._createPane('leaflet-popup-pane'); - - var zoomHide = ' leaflet-zoom-hide'; - - if (!this.options.markerZoomAnimation) { - L.DomUtil.addClass(panes.markerPane, zoomHide); - L.DomUtil.addClass(panes.shadowPane, zoomHide); - L.DomUtil.addClass(panes.popupPane, zoomHide); - } - }, - - _createPane: function (className, container) { - return L.DomUtil.create('div', className, container || this._panes.objectsPane); - }, - - _clearPanes: function () { - this._container.removeChild(this._mapPane); - }, - - _addLayers: function (layers) { - layers = layers ? (L.Util.isArray(layers) ? layers : [layers]) : []; - - for (var i = 0, len = layers.length; i < len; i++) { - this.addLayer(layers[i]); - } - }, - - - // private methods that modify map state - - _resetView: function (center, zoom, preserveMapOffset, afterZoomAnim) { - - var zoomChanged = (this._zoom !== zoom); - - if (!afterZoomAnim) { - this.fire('movestart'); - - if (zoomChanged) { - this.fire('zoomstart'); - } - } - - this._zoom = zoom; - this._initialCenter = center; - - this._initialTopLeftPoint = this._getNewTopLeftPoint(center); - - if (!preserveMapOffset) { - L.DomUtil.setPosition(this._mapPane, new L.Point(0, 0)); - } else { - this._initialTopLeftPoint._add(this._getMapPanePos()); - } - - this._tileLayersToLoad = this._tileLayersNum; - - var loading = !this._loaded; - this._loaded = true; - - this.fire('viewreset', {hard: !preserveMapOffset}); - - if (loading) { - this.fire('load'); - this.eachLayer(this._layerAdd, this); - } - - this.fire('move'); - - if (zoomChanged || afterZoomAnim) { - this.fire('zoomend'); - } - - this.fire('moveend', {hard: !preserveMapOffset}); - }, - - _rawPanBy: function (offset) { - L.DomUtil.setPosition(this._mapPane, this._getMapPanePos().subtract(offset)); - }, - - _getZoomSpan: function () { - return this.getMaxZoom() - this.getMinZoom(); - }, - - _updateZoomLevels: function () { - var i, - minZoom = Infinity, - maxZoom = -Infinity, - oldZoomSpan = this._getZoomSpan(); - - for (i in this._zoomBoundLayers) { - var layer = this._zoomBoundLayers[i]; - if (!isNaN(layer.options.minZoom)) { - minZoom = Math.min(minZoom, layer.options.minZoom); - } - if (!isNaN(layer.options.maxZoom)) { - maxZoom = Math.max(maxZoom, layer.options.maxZoom); - } - } - - if (i === undefined) { // we have no tilelayers - this._layersMaxZoom = this._layersMinZoom = undefined; - } else { - this._layersMaxZoom = maxZoom; - this._layersMinZoom = minZoom; - } - - if (oldZoomSpan !== this._getZoomSpan()) { - this.fire('zoomlevelschange'); - } - }, - - _panInsideMaxBounds: function () { - this.panInsideBounds(this.options.maxBounds); - }, - - _checkIfLoaded: function () { - if (!this._loaded) { - throw new Error('Set map center and zoom first.'); - } - }, - - // map events - - _initEvents: function (onOff) { - if (!L.DomEvent) { return; } - - onOff = onOff || 'on'; - - L.DomEvent[onOff](this._container, 'click', this._onMouseClick, this); - - var events = ['dblclick', 'mousedown', 'mouseup', 'mouseenter', - 'mouseleave', 'mousemove', 'contextmenu'], - i, len; - - for (i = 0, len = events.length; i < len; i++) { - L.DomEvent[onOff](this._container, events[i], this._fireMouseEvent, this); - } - - if (this.options.trackResize) { - L.DomEvent[onOff](window, 'resize', this._onResize, this); - } - }, - - _onResize: function () { - L.Util.cancelAnimFrame(this._resizeRequest); - this._resizeRequest = L.Util.requestAnimFrame( - function () { this.invalidateSize({debounceMoveend: true}); }, this, false, this._container); - }, - - _onMouseClick: function (e) { - if (!this._loaded || (!e._simulated && - ((this.dragging && this.dragging.moved()) || - (this.boxZoom && this.boxZoom.moved()))) || - L.DomEvent._skipped(e)) { return; } - - this.fire('preclick'); - this._fireMouseEvent(e); - }, - - _fireMouseEvent: function (e) { - if (!this._loaded || L.DomEvent._skipped(e)) { return; } - - var type = e.type; - - type = (type === 'mouseenter' ? 'mouseover' : (type === 'mouseleave' ? 'mouseout' : type)); - - if (!this.hasEventListeners(type)) { return; } - - if (type === 'contextmenu') { - L.DomEvent.preventDefault(e); - } - - var containerPoint = this.mouseEventToContainerPoint(e), - layerPoint = this.containerPointToLayerPoint(containerPoint), - latlng = this.layerPointToLatLng(layerPoint); - - this.fire(type, { - latlng: latlng, - layerPoint: layerPoint, - containerPoint: containerPoint, - originalEvent: e - }); - }, - - _onTileLayerLoad: function () { - this._tileLayersToLoad--; - if (this._tileLayersNum && !this._tileLayersToLoad) { - this.fire('tilelayersload'); - } - }, - - _clearHandlers: function () { - for (var i = 0, len = this._handlers.length; i < len; i++) { - this._handlers[i].disable(); - } - }, - - whenReady: function (callback, context) { - if (this._loaded) { - callback.call(context || this, this); - } else { - this.on('load', callback, context); - } - return this; - }, - - _layerAdd: function (layer) { - layer.onAdd(this); - this.fire('layeradd', {layer: layer}); - }, - - - // private methods for getting map state - - _getMapPanePos: function () { - return L.DomUtil.getPosition(this._mapPane); - }, - - _moved: function () { - var pos = this._getMapPanePos(); - return pos && !pos.equals([0, 0]); - }, - - _getTopLeftPoint: function () { - return this.getPixelOrigin().subtract(this._getMapPanePos()); - }, - - _getNewTopLeftPoint: function (center, zoom) { - var viewHalf = this.getSize()._divideBy(2); - // TODO round on display, not calculation to increase precision? - return this.project(center, zoom)._subtract(viewHalf)._round(); - }, - - _latLngToNewLayerPoint: function (latlng, newZoom, newCenter) { - var topLeft = this._getNewTopLeftPoint(newCenter, newZoom).add(this._getMapPanePos()); - return this.project(latlng, newZoom)._subtract(topLeft); - }, - - // layer point of the current center - _getCenterLayerPoint: function () { - return this.containerPointToLayerPoint(this.getSize()._divideBy(2)); - }, - - // offset of the specified place to the current center in pixels - _getCenterOffset: function (latlng) { - return this.latLngToLayerPoint(latlng).subtract(this._getCenterLayerPoint()); - }, - - // adjust center for view to get inside bounds - _limitCenter: function (center, zoom, bounds) { - - if (!bounds) { return center; } - - var centerPoint = this.project(center, zoom), - viewHalf = this.getSize().divideBy(2), - viewBounds = new L.Bounds(centerPoint.subtract(viewHalf), centerPoint.add(viewHalf)), - offset = this._getBoundsOffset(viewBounds, bounds, zoom); - - return this.unproject(centerPoint.add(offset), zoom); - }, - - // adjust offset for view to get inside bounds - _limitOffset: function (offset, bounds) { - if (!bounds) { return offset; } - - var viewBounds = this.getPixelBounds(), - newBounds = new L.Bounds(viewBounds.min.add(offset), viewBounds.max.add(offset)); - - return offset.add(this._getBoundsOffset(newBounds, bounds)); - }, - - // returns offset needed for pxBounds to get inside maxBounds at a specified zoom - _getBoundsOffset: function (pxBounds, maxBounds, zoom) { - var nwOffset = this.project(maxBounds.getNorthWest(), zoom).subtract(pxBounds.min), - seOffset = this.project(maxBounds.getSouthEast(), zoom).subtract(pxBounds.max), - - dx = this._rebound(nwOffset.x, -seOffset.x), - dy = this._rebound(nwOffset.y, -seOffset.y); - - return new L.Point(dx, dy); - }, - - _rebound: function (left, right) { - return left + right > 0 ? - Math.round(left - right) / 2 : - Math.max(0, Math.ceil(left)) - Math.max(0, Math.floor(right)); - }, - - _limitZoom: function (zoom) { - var min = this.getMinZoom(), - max = this.getMaxZoom(); - - return Math.max(min, Math.min(max, zoom)); - } -}); - -L.map = function (id, options) { - return new L.Map(id, options); -}; - - -/* - * Mercator projection that takes into account that the Earth is not a perfect sphere. - * Less popular than spherical mercator; used by projections like EPSG:3395. - */ - -L.Projection.Mercator = { - MAX_LATITUDE: 85.0840591556, - - R_MINOR: 6356752.314245179, - R_MAJOR: 6378137, - - project: function (latlng) { // (LatLng) -> Point - var d = L.LatLng.DEG_TO_RAD, - max = this.MAX_LATITUDE, - lat = Math.max(Math.min(max, latlng.lat), -max), - r = this.R_MAJOR, - r2 = this.R_MINOR, - x = latlng.lng * d * r, - y = lat * d, - tmp = r2 / r, - eccent = Math.sqrt(1.0 - tmp * tmp), - con = eccent * Math.sin(y); - - con = Math.pow((1 - con) / (1 + con), eccent * 0.5); - - var ts = Math.tan(0.5 * ((Math.PI * 0.5) - y)) / con; - y = -r * Math.log(ts); - - return new L.Point(x, y); - }, - - unproject: function (point) { // (Point, Boolean) -> LatLng - var d = L.LatLng.RAD_TO_DEG, - r = this.R_MAJOR, - r2 = this.R_MINOR, - lng = point.x * d / r, - tmp = r2 / r, - eccent = Math.sqrt(1 - (tmp * tmp)), - ts = Math.exp(- point.y / r), - phi = (Math.PI / 2) - 2 * Math.atan(ts), - numIter = 15, - tol = 1e-7, - i = numIter, - dphi = 0.1, - con; - - while ((Math.abs(dphi) > tol) && (--i > 0)) { - con = eccent * Math.sin(phi); - dphi = (Math.PI / 2) - 2 * Math.atan(ts * - Math.pow((1.0 - con) / (1.0 + con), 0.5 * eccent)) - phi; - phi += dphi; - } - - return new L.LatLng(phi * d, lng); - } -}; - - - -L.CRS.EPSG3395 = L.extend({}, L.CRS, { - code: 'EPSG:3395', - - projection: L.Projection.Mercator, - - transformation: (function () { - var m = L.Projection.Mercator, - r = m.R_MAJOR, - scale = 0.5 / (Math.PI * r); - - return new L.Transformation(scale, 0.5, -scale, 0.5); - }()) -}); - - -/* - * L.TileLayer is used for standard xyz-numbered tile layers. - */ - -L.TileLayer = L.Class.extend({ - includes: L.Mixin.Events, - - options: { - minZoom: 0, - maxZoom: 18, - tileSize: 256, - subdomains: 'abc', - errorTileUrl: '', - attribution: '', - zoomOffset: 0, - opacity: 1, - /* - maxNativeZoom: null, - zIndex: null, - tms: false, - continuousWorld: false, - noWrap: false, - zoomReverse: false, - detectRetina: false, - reuseTiles: false, - bounds: false, - */ - unloadInvisibleTiles: L.Browser.mobile, - updateWhenIdle: L.Browser.mobile - }, - - initialize: function (url, options) { - options = L.setOptions(this, options); - - // detecting retina displays, adjusting tileSize and zoom levels - if (options.detectRetina && L.Browser.retina && options.maxZoom > 0) { - - options.tileSize = Math.floor(options.tileSize / 2); - options.zoomOffset++; - - if (options.minZoom > 0) { - options.minZoom--; - } - this.options.maxZoom--; - } - - if (options.bounds) { - options.bounds = L.latLngBounds(options.bounds); - } - - this._url = url; - - var subdomains = this.options.subdomains; - - if (typeof subdomains === 'string') { - this.options.subdomains = subdomains.split(''); - } - }, - - onAdd: function (map) { - this._map = map; - this._animated = map._zoomAnimated; - - // create a container div for tiles - this._initContainer(); - - // set up events - map.on({ - 'viewreset': this._reset, - 'moveend': this._update - }, this); - - if (this._animated) { - map.on({ - 'zoomanim': this._animateZoom, - 'zoomend': this._endZoomAnim - }, this); - } - - if (!this.options.updateWhenIdle) { - this._limitedUpdate = L.Util.limitExecByInterval(this._update, 150, this); - map.on('move', this._limitedUpdate, this); - } - - this._reset(); - this._update(); - }, - - addTo: function (map) { - map.addLayer(this); - return this; - }, - - onRemove: function (map) { - this._container.parentNode.removeChild(this._container); - - map.off({ - 'viewreset': this._reset, - 'moveend': this._update - }, this); - - if (this._animated) { - map.off({ - 'zoomanim': this._animateZoom, - 'zoomend': this._endZoomAnim - }, this); - } - - if (!this.options.updateWhenIdle) { - map.off('move', this._limitedUpdate, this); - } - - this._container = null; - this._map = null; - }, - - bringToFront: function () { - var pane = this._map._panes.tilePane; - - if (this._container) { - pane.appendChild(this._container); - this._setAutoZIndex(pane, Math.max); - } - - return this; - }, - - bringToBack: function () { - var pane = this._map._panes.tilePane; - - if (this._container) { - pane.insertBefore(this._container, pane.firstChild); - this._setAutoZIndex(pane, Math.min); - } - - return this; - }, - - getAttribution: function () { - return this.options.attribution; - }, - - getContainer: function () { - return this._container; - }, - - setOpacity: function (opacity) { - this.options.opacity = opacity; - - if (this._map) { - this._updateOpacity(); - } - - return this; - }, - - setZIndex: function (zIndex) { - this.options.zIndex = zIndex; - this._updateZIndex(); - - return this; - }, - - setUrl: function (url, noRedraw) { - this._url = url; - - if (!noRedraw) { - this.redraw(); - } - - return this; - }, - - redraw: function () { - if (this._map) { - this._reset({hard: true}); - this._update(); - } - return this; - }, - - _updateZIndex: function () { - if (this._container && this.options.zIndex !== undefined) { - this._container.style.zIndex = this.options.zIndex; - } - }, - - _setAutoZIndex: function (pane, compare) { - - var layers = pane.children, - edgeZIndex = -compare(Infinity, -Infinity), // -Infinity for max, Infinity for min - zIndex, i, len; - - for (i = 0, len = layers.length; i < len; i++) { - - if (layers[i] !== this._container) { - zIndex = parseInt(layers[i].style.zIndex, 10); - - if (!isNaN(zIndex)) { - edgeZIndex = compare(edgeZIndex, zIndex); - } - } - } - - this.options.zIndex = this._container.style.zIndex = - (isFinite(edgeZIndex) ? edgeZIndex : 0) + compare(1, -1); - }, - - _updateOpacity: function () { - var i, - tiles = this._tiles; - - if (L.Browser.ielt9) { - for (i in tiles) { - L.DomUtil.setOpacity(tiles[i], this.options.opacity); - } - } else { - L.DomUtil.setOpacity(this._container, this.options.opacity); - } - }, - - _initContainer: function () { - var tilePane = this._map._panes.tilePane; - - if (!this._container) { - this._container = L.DomUtil.create('div', 'leaflet-layer'); - - this._updateZIndex(); - - if (this._animated) { - var className = 'leaflet-tile-container'; - - this._bgBuffer = L.DomUtil.create('div', className, this._container); - this._tileContainer = L.DomUtil.create('div', className, this._container); - - } else { - this._tileContainer = this._container; - } - - tilePane.appendChild(this._container); - - if (this.options.opacity < 1) { - this._updateOpacity(); - } - } - }, - - _reset: function (e) { - for (var key in this._tiles) { - this.fire('tileunload', {tile: this._tiles[key]}); - } - - this._tiles = {}; - this._tilesToLoad = 0; - - if (this.options.reuseTiles) { - this._unusedTiles = []; - } - - this._tileContainer.innerHTML = ''; - - if (this._animated && e && e.hard) { - this._clearBgBuffer(); - } - - this._initContainer(); - }, - - _getTileSize: function () { - var map = this._map, - zoom = map.getZoom() + this.options.zoomOffset, - zoomN = this.options.maxNativeZoom, - tileSize = this.options.tileSize; - - if (zoomN && zoom > zoomN) { - tileSize = Math.round(map.getZoomScale(zoom) / map.getZoomScale(zoomN) * tileSize); - } - - return tileSize; - }, - - _update: function () { - - if (!this._map) { return; } - - var map = this._map, - bounds = map.getPixelBounds(), - zoom = map.getZoom(), - tileSize = this._getTileSize(); - - if (zoom > this.options.maxZoom || zoom < this.options.minZoom) { - return; - } - - var tileBounds = L.bounds( - bounds.min.divideBy(tileSize)._floor(), - bounds.max.divideBy(tileSize)._floor()); - - this._addTilesFromCenterOut(tileBounds); - - if (this.options.unloadInvisibleTiles || this.options.reuseTiles) { - this._removeOtherTiles(tileBounds); - } - }, - - _addTilesFromCenterOut: function (bounds) { - var queue = [], - center = bounds.getCenter(); - - var j, i, point; - - for (j = bounds.min.y; j <= bounds.max.y; j++) { - for (i = bounds.min.x; i <= bounds.max.x; i++) { - point = new L.Point(i, j); - - if (this._tileShouldBeLoaded(point)) { - queue.push(point); - } - } - } - - var tilesToLoad = queue.length; - - if (tilesToLoad === 0) { return; } - - // load tiles in order of their distance to center - queue.sort(function (a, b) { - return a.distanceTo(center) - b.distanceTo(center); - }); - - var fragment = document.createDocumentFragment(); - - // if its the first batch of tiles to load - if (!this._tilesToLoad) { - this.fire('loading'); - } - - this._tilesToLoad += tilesToLoad; - - for (i = 0; i < tilesToLoad; i++) { - this._addTile(queue[i], fragment); - } - - this._tileContainer.appendChild(fragment); - }, - - _tileShouldBeLoaded: function (tilePoint) { - if ((tilePoint.x + ':' + tilePoint.y) in this._tiles) { - return false; // already loaded - } - - var options = this.options; - - if (!options.continuousWorld) { - var limit = this._getWrapTileNum(); - - // don't load if exceeds world bounds - if ((options.noWrap && (tilePoint.x < 0 || tilePoint.x >= limit.x)) || - tilePoint.y < 0 || tilePoint.y >= limit.y) { return false; } - } - - if (options.bounds) { - var tileSize = this._getTileSize(), - nwPoint = tilePoint.multiplyBy(tileSize), - sePoint = nwPoint.add([tileSize, tileSize]), - nw = this._map.unproject(nwPoint), - se = this._map.unproject(sePoint); - - // TODO temporary hack, will be removed after refactoring projections - // https://github.com/Leaflet/Leaflet/issues/1618 - if (!options.continuousWorld && !options.noWrap) { - nw = nw.wrap(); - se = se.wrap(); - } - - if (!options.bounds.intersects([nw, se])) { return false; } - } - - return true; - }, - - _removeOtherTiles: function (bounds) { - var kArr, x, y, key; - - for (key in this._tiles) { - kArr = key.split(':'); - x = parseInt(kArr[0], 10); - y = parseInt(kArr[1], 10); - - // remove tile if it's out of bounds - if (x < bounds.min.x || x > bounds.max.x || y < bounds.min.y || y > bounds.max.y) { - this._removeTile(key); - } - } - }, - - _removeTile: function (key) { - var tile = this._tiles[key]; - - this.fire('tileunload', {tile: tile, url: tile.src}); - - if (this.options.reuseTiles) { - L.DomUtil.removeClass(tile, 'leaflet-tile-loaded'); - this._unusedTiles.push(tile); - - } else if (tile.parentNode === this._tileContainer) { - this._tileContainer.removeChild(tile); - } - - // for https://github.com/CloudMade/Leaflet/issues/137 - if (!L.Browser.android) { - tile.onload = null; - tile.src = L.Util.emptyImageUrl; - } - - delete this._tiles[key]; - }, - - _addTile: function (tilePoint, container) { - var tilePos = this._getTilePos(tilePoint); - - // get unused tile - or create a new tile - var tile = this._getTile(); - - /* - Chrome 20 layouts much faster with top/left (verify with timeline, frames) - Android 4 browser has display issues with top/left and requires transform instead - (other browsers don't currently care) - see debug/hacks/jitter.html for an example - */ - L.DomUtil.setPosition(tile, tilePos, L.Browser.chrome); - - this._tiles[tilePoint.x + ':' + tilePoint.y] = tile; - - this._loadTile(tile, tilePoint); - - if (tile.parentNode !== this._tileContainer) { - container.appendChild(tile); - } - }, - - _getZoomForUrl: function () { - - var options = this.options, - zoom = this._map.getZoom(); - - if (options.zoomReverse) { - zoom = options.maxZoom - zoom; - } - - zoom += options.zoomOffset; - - return options.maxNativeZoom ? Math.min(zoom, options.maxNativeZoom) : zoom; - }, - - _getTilePos: function (tilePoint) { - var origin = this._map.getPixelOrigin(), - tileSize = this._getTileSize(); - - return tilePoint.multiplyBy(tileSize).subtract(origin); - }, - - // image-specific code (override to implement e.g. Canvas or SVG tile layer) - - getTileUrl: function (tilePoint) { - return L.Util.template(this._url, L.extend({ - s: this._getSubdomain(tilePoint), - z: tilePoint.z, - x: tilePoint.x, - y: tilePoint.y - }, this.options)); - }, - - _getWrapTileNum: function () { - var crs = this._map.options.crs, - size = crs.getSize(this._map.getZoom()); - return size.divideBy(this._getTileSize())._floor(); - }, - - _adjustTilePoint: function (tilePoint) { - - var limit = this._getWrapTileNum(); - - // wrap tile coordinates - if (!this.options.continuousWorld && !this.options.noWrap) { - tilePoint.x = ((tilePoint.x % limit.x) + limit.x) % limit.x; - } - - if (this.options.tms) { - tilePoint.y = limit.y - tilePoint.y - 1; - } - - tilePoint.z = this._getZoomForUrl(); - }, - - _getSubdomain: function (tilePoint) { - var index = Math.abs(tilePoint.x + tilePoint.y) % this.options.subdomains.length; - return this.options.subdomains[index]; - }, - - _getTile: function () { - if (this.options.reuseTiles && this._unusedTiles.length > 0) { - var tile = this._unusedTiles.pop(); - this._resetTile(tile); - return tile; - } - return this._createTile(); - }, - - // Override if data stored on a tile needs to be cleaned up before reuse - _resetTile: function (/*tile*/) {}, - - _createTile: function () { - var tile = L.DomUtil.create('img', 'leaflet-tile'); - tile.style.width = tile.style.height = this._getTileSize() + 'px'; - tile.galleryimg = 'no'; - - tile.onselectstart = tile.onmousemove = L.Util.falseFn; - - if (L.Browser.ielt9 && this.options.opacity !== undefined) { - L.DomUtil.setOpacity(tile, this.options.opacity); - } - // without this hack, tiles disappear after zoom on Chrome for Android - // https://github.com/Leaflet/Leaflet/issues/2078 - if (L.Browser.mobileWebkit3d) { - tile.style.WebkitBackfaceVisibility = 'hidden'; - } - return tile; - }, - - _loadTile: function (tile, tilePoint) { - tile._layer = this; - tile.onload = this._tileOnLoad; - tile.onerror = this._tileOnError; - - this._adjustTilePoint(tilePoint); - tile.src = this.getTileUrl(tilePoint); - - this.fire('tileloadstart', { - tile: tile, - url: tile.src - }); - }, - - _tileLoaded: function () { - this._tilesToLoad--; - - if (this._animated) { - L.DomUtil.addClass(this._tileContainer, 'leaflet-zoom-animated'); - } - - if (!this._tilesToLoad) { - this.fire('load'); - - if (this._animated) { - // clear scaled tiles after all new tiles are loaded (for performance) - clearTimeout(this._clearBgBufferTimer); - this._clearBgBufferTimer = setTimeout(L.bind(this._clearBgBuffer, this), 500); - } - } - }, - - _tileOnLoad: function () { - var layer = this._layer; - - //Only if we are loading an actual image - if (this.src !== L.Util.emptyImageUrl) { - L.DomUtil.addClass(this, 'leaflet-tile-loaded'); - - layer.fire('tileload', { - tile: this, - url: this.src - }); - } - - layer._tileLoaded(); - }, - - _tileOnError: function () { - var layer = this._layer; - - layer.fire('tileerror', { - tile: this, - url: this.src - }); - - var newUrl = layer.options.errorTileUrl; - if (newUrl) { - this.src = newUrl; - } - - layer._tileLoaded(); - } -}); - -L.tileLayer = function (url, options) { - return new L.TileLayer(url, options); -}; - - -/* - * L.TileLayer.WMS is used for putting WMS tile layers on the map. - */ - -L.TileLayer.WMS = L.TileLayer.extend({ - - defaultWmsParams: { - service: 'WMS', - request: 'GetMap', - version: '1.1.1', - layers: '', - styles: '', - format: 'image/jpeg', - transparent: false - }, - - initialize: function (url, options) { // (String, Object) - - this._url = url; - - var wmsParams = L.extend({}, this.defaultWmsParams), - tileSize = options.tileSize || this.options.tileSize; - - if (options.detectRetina && L.Browser.retina) { - wmsParams.width = wmsParams.height = tileSize * 2; - } else { - wmsParams.width = wmsParams.height = tileSize; - } - - for (var i in options) { - // all keys that are not TileLayer options go to WMS params - if (!this.options.hasOwnProperty(i) && i !== 'crs') { - wmsParams[i] = options[i]; - } - } - - this.wmsParams = wmsParams; - - L.setOptions(this, options); - }, - - onAdd: function (map) { - - this._crs = this.options.crs || map.options.crs; - - this._wmsVersion = parseFloat(this.wmsParams.version); - - var projectionKey = this._wmsVersion >= 1.3 ? 'crs' : 'srs'; - this.wmsParams[projectionKey] = this._crs.code; - - L.TileLayer.prototype.onAdd.call(this, map); - }, - - getTileUrl: function (tilePoint) { // (Point, Number) -> String - - var map = this._map, - tileSize = this.options.tileSize, - - nwPoint = tilePoint.multiplyBy(tileSize), - sePoint = nwPoint.add([tileSize, tileSize]), - - nw = this._crs.project(map.unproject(nwPoint, tilePoint.z)), - se = this._crs.project(map.unproject(sePoint, tilePoint.z)), - bbox = this._wmsVersion >= 1.3 && this._crs === L.CRS.EPSG4326 ? - [se.y, nw.x, nw.y, se.x].join(',') : - [nw.x, se.y, se.x, nw.y].join(','), - - url = L.Util.template(this._url, {s: this._getSubdomain(tilePoint)}); - - return url + L.Util.getParamString(this.wmsParams, url, true) + '&BBOX=' + bbox; - }, - - setParams: function (params, noRedraw) { - - L.extend(this.wmsParams, params); - - if (!noRedraw) { - this.redraw(); - } - - return this; - } -}); - -L.tileLayer.wms = function (url, options) { - return new L.TileLayer.WMS(url, options); -}; - - -/* - * L.TileLayer.Canvas is a class that you can use as a base for creating - * dynamically drawn Canvas-based tile layers. - */ - -L.TileLayer.Canvas = L.TileLayer.extend({ - options: { - async: false - }, - - initialize: function (options) { - L.setOptions(this, options); - }, - - redraw: function () { - if (this._map) { - this._reset({hard: true}); - this._update(); - } - - for (var i in this._tiles) { - this._redrawTile(this._tiles[i]); - } - return this; - }, - - _redrawTile: function (tile) { - this.drawTile(tile, tile._tilePoint, this._map._zoom); - }, - - _createTile: function () { - var tile = L.DomUtil.create('canvas', 'leaflet-tile'); - tile.width = tile.height = this.options.tileSize; - tile.onselectstart = tile.onmousemove = L.Util.falseFn; - return tile; - }, - - _loadTile: function (tile, tilePoint) { - tile._layer = this; - tile._tilePoint = tilePoint; - - this._redrawTile(tile); - - if (!this.options.async) { - this.tileDrawn(tile); - } - }, - - drawTile: function (/*tile, tilePoint*/) { - // override with rendering code - }, - - tileDrawn: function (tile) { - this._tileOnLoad.call(tile); - } -}); - - -L.tileLayer.canvas = function (options) { - return new L.TileLayer.Canvas(options); -}; - - -/* - * L.ImageOverlay is used to overlay images over the map (to specific geographical bounds). - */ - -L.ImageOverlay = L.Class.extend({ - includes: L.Mixin.Events, - - options: { - opacity: 1 - }, - - initialize: function (url, bounds, options) { // (String, LatLngBounds, Object) - this._url = url; - this._bounds = L.latLngBounds(bounds); - - L.setOptions(this, options); - }, - - onAdd: function (map) { - this._map = map; - - if (!this._image) { - this._initImage(); - } - - map._panes.overlayPane.appendChild(this._image); - - map.on('viewreset', this._reset, this); - - if (map.options.zoomAnimation && L.Browser.any3d) { - map.on('zoomanim', this._animateZoom, this); - } - - this._reset(); - }, - - onRemove: function (map) { - map.getPanes().overlayPane.removeChild(this._image); - - map.off('viewreset', this._reset, this); - - if (map.options.zoomAnimation) { - map.off('zoomanim', this._animateZoom, this); - } - }, - - addTo: function (map) { - map.addLayer(this); - return this; - }, - - setOpacity: function (opacity) { - this.options.opacity = opacity; - this._updateOpacity(); - return this; - }, - - // TODO remove bringToFront/bringToBack duplication from TileLayer/Path - bringToFront: function () { - if (this._image) { - this._map._panes.overlayPane.appendChild(this._image); - } - return this; - }, - - bringToBack: function () { - var pane = this._map._panes.overlayPane; - if (this._image) { - pane.insertBefore(this._image, pane.firstChild); - } - return this; - }, - - setUrl: function (url) { - this._url = url; - this._image.src = this._url; - }, - - getAttribution: function () { - return this.options.attribution; - }, - - _initImage: function () { - this._image = L.DomUtil.create('img', 'leaflet-image-layer'); - - if (this._map.options.zoomAnimation && L.Browser.any3d) { - L.DomUtil.addClass(this._image, 'leaflet-zoom-animated'); - } else { - L.DomUtil.addClass(this._image, 'leaflet-zoom-hide'); - } - - this._updateOpacity(); - - //TODO createImage util method to remove duplication - L.extend(this._image, { - galleryimg: 'no', - onselectstart: L.Util.falseFn, - onmousemove: L.Util.falseFn, - onload: L.bind(this._onImageLoad, this), - src: this._url - }); - }, - - _animateZoom: function (e) { - var map = this._map, - image = this._image, - scale = map.getZoomScale(e.zoom), - nw = this._bounds.getNorthWest(), - se = this._bounds.getSouthEast(), - - topLeft = map._latLngToNewLayerPoint(nw, e.zoom, e.center), - size = map._latLngToNewLayerPoint(se, e.zoom, e.center)._subtract(topLeft), - origin = topLeft._add(size._multiplyBy((1 / 2) * (1 - 1 / scale))); - - image.style[L.DomUtil.TRANSFORM] = - L.DomUtil.getTranslateString(origin) + ' scale(' + scale + ') '; - }, - - _reset: function () { - var image = this._image, - topLeft = this._map.latLngToLayerPoint(this._bounds.getNorthWest()), - size = this._map.latLngToLayerPoint(this._bounds.getSouthEast())._subtract(topLeft); - - L.DomUtil.setPosition(image, topLeft); - - image.style.width = size.x + 'px'; - image.style.height = size.y + 'px'; - }, - - _onImageLoad: function () { - this.fire('load'); - }, - - _updateOpacity: function () { - L.DomUtil.setOpacity(this._image, this.options.opacity); - } -}); - -L.imageOverlay = function (url, bounds, options) { - return new L.ImageOverlay(url, bounds, options); -}; - - -/* - * L.Icon is an image-based icon class that you can use with L.Marker for custom markers. - */ - -L.Icon = L.Class.extend({ - options: { - /* - iconUrl: (String) (required) - iconRetinaUrl: (String) (optional, used for retina devices if detected) - iconSize: (Point) (can be set through CSS) - iconAnchor: (Point) (centered by default, can be set in CSS with negative margins) - popupAnchor: (Point) (if not specified, popup opens in the anchor point) - shadowUrl: (String) (no shadow by default) - shadowRetinaUrl: (String) (optional, used for retina devices if detected) - shadowSize: (Point) - shadowAnchor: (Point) - */ - className: '' - }, - - initialize: function (options) { - L.setOptions(this, options); - }, - - createIcon: function (oldIcon) { - return this._createIcon('icon', oldIcon); - }, - - createShadow: function (oldIcon) { - return this._createIcon('shadow', oldIcon); - }, - - _createIcon: function (name, oldIcon) { - var src = this._getIconUrl(name); - - if (!src) { - if (name === 'icon') { - throw new Error('iconUrl not set in Icon options (see the docs).'); - } - return null; - } - - var img; - if (!oldIcon || oldIcon.tagName !== 'IMG') { - img = this._createImg(src); - } else { - img = this._createImg(src, oldIcon); - } - this._setIconStyles(img, name); - - return img; - }, - - _setIconStyles: function (img, name) { - var options = this.options, - size = L.point(options[name + 'Size']), - anchor; - - if (name === 'shadow') { - anchor = L.point(options.shadowAnchor || options.iconAnchor); - } else { - anchor = L.point(options.iconAnchor); - } - - if (!anchor && size) { - anchor = size.divideBy(2, true); - } - - img.className = 'leaflet-marker-' + name + ' ' + options.className; - - if (anchor) { - img.style.marginLeft = (-anchor.x) + 'px'; - img.style.marginTop = (-anchor.y) + 'px'; - } - - if (size) { - img.style.width = size.x + 'px'; - img.style.height = size.y + 'px'; - } - }, - - _createImg: function (src, el) { - el = el || document.createElement('img'); - el.src = src; - return el; - }, - - _getIconUrl: function (name) { - if (L.Browser.retina && this.options[name + 'RetinaUrl']) { - return this.options[name + 'RetinaUrl']; - } - return this.options[name + 'Url']; - } -}); - -L.icon = function (options) { - return new L.Icon(options); -}; - - -/* - * L.Icon.Default is the blue marker icon used by default in Leaflet. - */ - -L.Icon.Default = L.Icon.extend({ - - options: { - iconSize: [25, 41], - iconAnchor: [12, 41], - popupAnchor: [1, -34], - - shadowSize: [41, 41] - }, - - _getIconUrl: function (name) { - var key = name + 'Url'; - - if (this.options[key]) { - return this.options[key]; - } - - if (L.Browser.retina && name === 'icon') { - name += '-2x'; - } - - var path = L.Icon.Default.imagePath; - - if (!path) { - throw new Error('Couldn\'t autodetect L.Icon.Default.imagePath, set it manually.'); - } - - return path + '/marker-' + name + '.png'; - } -}); - -L.Icon.Default.imagePath = (function () { - var scripts = document.getElementsByTagName('script'), - leafletRe = /[\/^]leaflet[\-\._]?([\w\-\._]*)\.js\??/; - - var i, len, src, matches, path; - - for (i = 0, len = scripts.length; i < len; i++) { - src = scripts[i].src; - matches = src.match(leafletRe); - - if (matches) { - path = src.split(leafletRe)[0]; - return (path ? path + '/' : '') + 'images'; - } - } -}()); - - -/* - * L.Marker is used to display clickable/draggable icons on the map. - */ - -L.Marker = L.Class.extend({ - - includes: L.Mixin.Events, - - options: { - icon: new L.Icon.Default(), - title: '', - alt: '', - clickable: true, - draggable: false, - keyboard: true, - zIndexOffset: 0, - opacity: 1, - riseOnHover: false, - riseOffset: 250 - }, - - initialize: function (latlng, options) { - L.setOptions(this, options); - this._latlng = L.latLng(latlng); - }, - - onAdd: function (map) { - this._map = map; - - map.on('viewreset', this.update, this); - - this._initIcon(); - this.update(); - this.fire('add'); - - if (map.options.zoomAnimation && map.options.markerZoomAnimation) { - map.on('zoomanim', this._animateZoom, this); - } - }, - - addTo: function (map) { - map.addLayer(this); - return this; - }, - - onRemove: function (map) { - if (this.dragging) { - this.dragging.disable(); - } - - this._removeIcon(); - this._removeShadow(); - - this.fire('remove'); - - map.off({ - 'viewreset': this.update, - 'zoomanim': this._animateZoom - }, this); - - this._map = null; - }, - - getLatLng: function () { - return this._latlng; - }, - - setLatLng: function (latlng) { - this._latlng = L.latLng(latlng); - - this.update(); - - return this.fire('move', { latlng: this._latlng }); - }, - - setZIndexOffset: function (offset) { - this.options.zIndexOffset = offset; - this.update(); - - return this; - }, - - setIcon: function (icon) { - - this.options.icon = icon; - - if (this._map) { - this._initIcon(); - this.update(); - } - - if (this._popup) { - this.bindPopup(this._popup); - } - - return this; - }, - - update: function () { - if (this._icon) { - this._setPos(this._map.latLngToLayerPoint(this._latlng).round()); - } - return this; - }, - - _initIcon: function () { - var options = this.options, - map = this._map, - animation = (map.options.zoomAnimation && map.options.markerZoomAnimation), - classToAdd = animation ? 'leaflet-zoom-animated' : 'leaflet-zoom-hide'; - - var icon = options.icon.createIcon(this._icon), - addIcon = false; - - // if we're not reusing the icon, remove the old one and init new one - if (icon !== this._icon) { - if (this._icon) { - this._removeIcon(); - } - addIcon = true; - - if (options.title) { - icon.title = options.title; - } - - if (options.alt) { - icon.alt = options.alt; - } - } - - L.DomUtil.addClass(icon, classToAdd); - - if (options.keyboard) { - icon.tabIndex = '0'; - } - - this._icon = icon; - - this._initInteraction(); - - if (options.riseOnHover) { - L.DomEvent - .on(icon, 'mouseover', this._bringToFront, this) - .on(icon, 'mouseout', this._resetZIndex, this); - } - - var newShadow = options.icon.createShadow(this._shadow), - addShadow = false; - - if (newShadow !== this._shadow) { - this._removeShadow(); - addShadow = true; - } - - if (newShadow) { - L.DomUtil.addClass(newShadow, classToAdd); - } - this._shadow = newShadow; - - - if (options.opacity < 1) { - this._updateOpacity(); - } - - - var panes = this._map._panes; - - if (addIcon) { - panes.markerPane.appendChild(this._icon); - } - - if (newShadow && addShadow) { - panes.shadowPane.appendChild(this._shadow); - } - }, - - _removeIcon: function () { - if (this.options.riseOnHover) { - L.DomEvent - .off(this._icon, 'mouseover', this._bringToFront) - .off(this._icon, 'mouseout', this._resetZIndex); - } - - this._map._panes.markerPane.removeChild(this._icon); - - this._icon = null; - }, - - _removeShadow: function () { - if (this._shadow) { - this._map._panes.shadowPane.removeChild(this._shadow); - } - this._shadow = null; - }, - - _setPos: function (pos) { - L.DomUtil.setPosition(this._icon, pos); - - if (this._shadow) { - L.DomUtil.setPosition(this._shadow, pos); - } - - this._zIndex = pos.y + this.options.zIndexOffset; - - this._resetZIndex(); - }, - - _updateZIndex: function (offset) { - this._icon.style.zIndex = this._zIndex + offset; - }, - - _animateZoom: function (opt) { - var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center).round(); - - this._setPos(pos); - }, - - _initInteraction: function () { - - if (!this.options.clickable) { return; } - - // TODO refactor into something shared with Map/Path/etc. to DRY it up - - var icon = this._icon, - events = ['dblclick', 'mousedown', 'mouseover', 'mouseout', 'contextmenu']; - - L.DomUtil.addClass(icon, 'leaflet-clickable'); - L.DomEvent.on(icon, 'click', this._onMouseClick, this); - L.DomEvent.on(icon, 'keypress', this._onKeyPress, this); - - for (var i = 0; i < events.length; i++) { - L.DomEvent.on(icon, events[i], this._fireMouseEvent, this); - } - - if (L.Handler.MarkerDrag) { - this.dragging = new L.Handler.MarkerDrag(this); - - if (this.options.draggable) { - this.dragging.enable(); - } - } - }, - - _onMouseClick: function (e) { - var wasDragged = this.dragging && this.dragging.moved(); - - if (this.hasEventListeners(e.type) || wasDragged) { - L.DomEvent.stopPropagation(e); - } - - if (wasDragged) { return; } - - if ((!this.dragging || !this.dragging._enabled) && this._map.dragging && this._map.dragging.moved()) { return; } - - this.fire(e.type, { - originalEvent: e, - latlng: this._latlng - }); - }, - - _onKeyPress: function (e) { - if (e.keyCode === 13) { - this.fire('click', { - originalEvent: e, - latlng: this._latlng - }); - } - }, - - _fireMouseEvent: function (e) { - - this.fire(e.type, { - originalEvent: e, - latlng: this._latlng - }); - - // TODO proper custom event propagation - // this line will always be called if marker is in a FeatureGroup - if (e.type === 'contextmenu' && this.hasEventListeners(e.type)) { - L.DomEvent.preventDefault(e); - } - if (e.type !== 'mousedown') { - L.DomEvent.stopPropagation(e); - } else { - L.DomEvent.preventDefault(e); - } - }, - - setOpacity: function (opacity) { - this.options.opacity = opacity; - if (this._map) { - this._updateOpacity(); - } - - return this; - }, - - _updateOpacity: function () { - L.DomUtil.setOpacity(this._icon, this.options.opacity); - if (this._shadow) { - L.DomUtil.setOpacity(this._shadow, this.options.opacity); - } - }, - - _bringToFront: function () { - this._updateZIndex(this.options.riseOffset); - }, - - _resetZIndex: function () { - this._updateZIndex(0); - } -}); - -L.marker = function (latlng, options) { - return new L.Marker(latlng, options); -}; - - -/* - * L.DivIcon is a lightweight HTML-based icon class (as opposed to the image-based L.Icon) - * to use with L.Marker. - */ - -L.DivIcon = L.Icon.extend({ - options: { - iconSize: [12, 12], // also can be set through CSS - /* - iconAnchor: (Point) - popupAnchor: (Point) - html: (String) - bgPos: (Point) - */ - className: 'leaflet-div-icon', - html: false - }, - - createIcon: function (oldIcon) { - var div = (oldIcon && oldIcon.tagName === 'DIV') ? oldIcon : document.createElement('div'), - options = this.options; - - if (options.html !== false) { - div.innerHTML = options.html; - } else { - div.innerHTML = ''; - } - - if (options.bgPos) { - div.style.backgroundPosition = - (-options.bgPos.x) + 'px ' + (-options.bgPos.y) + 'px'; - } - - this._setIconStyles(div, 'icon'); - return div; - }, - - createShadow: function () { - return null; - } -}); - -L.divIcon = function (options) { - return new L.DivIcon(options); -}; - - -/* - * L.Popup is used for displaying popups on the map. - */ - -L.Map.mergeOptions({ - closePopupOnClick: true -}); - -L.Popup = L.Class.extend({ - includes: L.Mixin.Events, - - options: { - minWidth: 50, - maxWidth: 300, - // maxHeight: null, - autoPan: true, - closeButton: true, - offset: [0, 7], - autoPanPadding: [5, 5], - // autoPanPaddingTopLeft: null, - // autoPanPaddingBottomRight: null, - keepInView: false, - className: '', - zoomAnimation: true - }, - - initialize: function (options, source) { - L.setOptions(this, options); - - this._source = source; - this._animated = L.Browser.any3d && this.options.zoomAnimation; - this._isOpen = false; - }, - - onAdd: function (map) { - this._map = map; - - if (!this._container) { - this._initLayout(); - } - - var animFade = map.options.fadeAnimation; - - if (animFade) { - L.DomUtil.setOpacity(this._container, 0); - } - map._panes.popupPane.appendChild(this._container); - - map.on(this._getEvents(), this); - - this.update(); - - if (animFade) { - L.DomUtil.setOpacity(this._container, 1); - } - - this.fire('open'); - - map.fire('popupopen', {popup: this}); - - if (this._source) { - this._source.fire('popupopen', {popup: this}); - } - }, - - addTo: function (map) { - map.addLayer(this); - return this; - }, - - openOn: function (map) { - map.openPopup(this); - return this; - }, - - onRemove: function (map) { - map._panes.popupPane.removeChild(this._container); - - L.Util.falseFn(this._container.offsetWidth); // force reflow - - map.off(this._getEvents(), this); - - if (map.options.fadeAnimation) { - L.DomUtil.setOpacity(this._container, 0); - } - - this._map = null; - - this.fire('close'); - - map.fire('popupclose', {popup: this}); - - if (this._source) { - this._source.fire('popupclose', {popup: this}); - } - }, - - getLatLng: function () { - return this._latlng; - }, - - setLatLng: function (latlng) { - this._latlng = L.latLng(latlng); - if (this._map) { - this._updatePosition(); - this._adjustPan(); - } - return this; - }, - - getContent: function () { - return this._content; - }, - - setContent: function (content) { - this._content = content; - this.update(); - return this; - }, - - update: function () { - if (!this._map) { return; } - - this._container.style.visibility = 'hidden'; - - this._updateContent(); - this._updateLayout(); - this._updatePosition(); - - this._container.style.visibility = ''; - - this._adjustPan(); - }, - - _getEvents: function () { - var events = { - viewreset: this._updatePosition - }; - - if (this._animated) { - events.zoomanim = this._zoomAnimation; - } - if ('closeOnClick' in this.options ? this.options.closeOnClick : this._map.options.closePopupOnClick) { - events.preclick = this._close; - } - if (this.options.keepInView) { - events.moveend = this._adjustPan; - } - - return events; - }, - - _close: function () { - if (this._map) { - this._map.closePopup(this); - } - }, - - _initLayout: function () { - var prefix = 'leaflet-popup', - containerClass = prefix + ' ' + this.options.className + ' leaflet-zoom-' + - (this._animated ? 'animated' : 'hide'), - container = this._container = L.DomUtil.create('div', containerClass), - closeButton; - - if (this.options.closeButton) { - closeButton = this._closeButton = - L.DomUtil.create('a', prefix + '-close-button', container); - closeButton.href = '#close'; - closeButton.innerHTML = '×'; - L.DomEvent.disableClickPropagation(closeButton); - - L.DomEvent.on(closeButton, 'click', this._onCloseButtonClick, this); - } - - var wrapper = this._wrapper = - L.DomUtil.create('div', prefix + '-content-wrapper', container); - L.DomEvent.disableClickPropagation(wrapper); - - this._contentNode = L.DomUtil.create('div', prefix + '-content', wrapper); - - L.DomEvent.disableScrollPropagation(this._contentNode); - L.DomEvent.on(wrapper, 'contextmenu', L.DomEvent.stopPropagation); - - this._tipContainer = L.DomUtil.create('div', prefix + '-tip-container', container); - this._tip = L.DomUtil.create('div', prefix + '-tip', this._tipContainer); - }, - - _updateContent: function () { - if (!this._content) { return; } - - if (typeof this._content === 'string') { - this._contentNode.innerHTML = this._content; - } else { - while (this._contentNode.hasChildNodes()) { - this._contentNode.removeChild(this._contentNode.firstChild); - } - this._contentNode.appendChild(this._content); - } - this.fire('contentupdate'); - }, - - _updateLayout: function () { - var container = this._contentNode, - style = container.style; - - style.width = ''; - style.whiteSpace = 'nowrap'; - - var width = container.offsetWidth; - width = Math.min(width, this.options.maxWidth); - width = Math.max(width, this.options.minWidth); - - style.width = (width + 1) + 'px'; - style.whiteSpace = ''; - - style.height = ''; - - var height = container.offsetHeight, - maxHeight = this.options.maxHeight, - scrolledClass = 'leaflet-popup-scrolled'; - - if (maxHeight && height > maxHeight) { - style.height = maxHeight + 'px'; - L.DomUtil.addClass(container, scrolledClass); - } else { - L.DomUtil.removeClass(container, scrolledClass); - } - - this._containerWidth = this._container.offsetWidth; - }, - - _updatePosition: function () { - if (!this._map) { return; } - - var pos = this._map.latLngToLayerPoint(this._latlng), - animated = this._animated, - offset = L.point(this.options.offset); - - if (animated) { - L.DomUtil.setPosition(this._container, pos); - } - - this._containerBottom = -offset.y - (animated ? 0 : pos.y); - this._containerLeft = -Math.round(this._containerWidth / 2) + offset.x + (animated ? 0 : pos.x); - - // bottom position the popup in case the height of the popup changes (images loading etc) - this._container.style.bottom = this._containerBottom + 'px'; - this._container.style.left = this._containerLeft + 'px'; - }, - - _zoomAnimation: function (opt) { - var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center); - - L.DomUtil.setPosition(this._container, pos); - }, - - _adjustPan: function () { - if (!this.options.autoPan) { return; } - - var map = this._map, - containerHeight = this._container.offsetHeight, - containerWidth = this._containerWidth, - - layerPos = new L.Point(this._containerLeft, -containerHeight - this._containerBottom); - - if (this._animated) { - layerPos._add(L.DomUtil.getPosition(this._container)); - } - - var containerPos = map.layerPointToContainerPoint(layerPos), - padding = L.point(this.options.autoPanPadding), - paddingTL = L.point(this.options.autoPanPaddingTopLeft || padding), - paddingBR = L.point(this.options.autoPanPaddingBottomRight || padding), - size = map.getSize(), - dx = 0, - dy = 0; - - if (containerPos.x + containerWidth + paddingBR.x > size.x) { // right - dx = containerPos.x + containerWidth - size.x + paddingBR.x; - } - if (containerPos.x - dx - paddingTL.x < 0) { // left - dx = containerPos.x - paddingTL.x; - } - if (containerPos.y + containerHeight + paddingBR.y > size.y) { // bottom - dy = containerPos.y + containerHeight - size.y + paddingBR.y; - } - if (containerPos.y - dy - paddingTL.y < 0) { // top - dy = containerPos.y - paddingTL.y; - } - - if (dx || dy) { - map - .fire('autopanstart') - .panBy([dx, dy]); - } - }, - - _onCloseButtonClick: function (e) { - this._close(); - L.DomEvent.stop(e); - } -}); - -L.popup = function (options, source) { - return new L.Popup(options, source); -}; - - -L.Map.include({ - openPopup: function (popup, latlng, options) { // (Popup) or (String || HTMLElement, LatLng[, Object]) - this.closePopup(); - - if (!(popup instanceof L.Popup)) { - var content = popup; - - popup = new L.Popup(options) - .setLatLng(latlng) - .setContent(content); - } - popup._isOpen = true; - - this._popup = popup; - return this.addLayer(popup); - }, - - closePopup: function (popup) { - if (!popup || popup === this._popup) { - popup = this._popup; - this._popup = null; - } - if (popup) { - this.removeLayer(popup); - popup._isOpen = false; - } - return this; - } -}); - - -/* - * Popup extension to L.Marker, adding popup-related methods. - */ - -L.Marker.include({ - openPopup: function () { - if (this._popup && this._map && !this._map.hasLayer(this._popup)) { - this._popup.setLatLng(this._latlng); - this._map.openPopup(this._popup); - } - - return this; - }, - - closePopup: function () { - if (this._popup) { - this._popup._close(); - } - return this; - }, - - togglePopup: function () { - if (this._popup) { - if (this._popup._isOpen) { - this.closePopup(); - } else { - this.openPopup(); - } - } - return this; - }, - - bindPopup: function (content, options) { - var anchor = L.point(this.options.icon.options.popupAnchor || [0, 0]); - - anchor = anchor.add(L.Popup.prototype.options.offset); - - if (options && options.offset) { - anchor = anchor.add(options.offset); - } - - options = L.extend({offset: anchor}, options); - - if (!this._popupHandlersAdded) { - this - .on('click', this.togglePopup, this) - .on('remove', this.closePopup, this) - .on('move', this._movePopup, this); - this._popupHandlersAdded = true; - } - - if (content instanceof L.Popup) { - L.setOptions(content, options); - this._popup = content; - content._source = this; - } else { - this._popup = new L.Popup(options, this) - .setContent(content); - } - - return this; - }, - - setPopupContent: function (content) { - if (this._popup) { - this._popup.setContent(content); - } - return this; - }, - - unbindPopup: function () { - if (this._popup) { - this._popup = null; - this - .off('click', this.togglePopup, this) - .off('remove', this.closePopup, this) - .off('move', this._movePopup, this); - this._popupHandlersAdded = false; - } - return this; - }, - - getPopup: function () { - return this._popup; - }, - - _movePopup: function (e) { - this._popup.setLatLng(e.latlng); - } -}); - - -/* - * L.LayerGroup is a class to combine several layers into one so that - * you can manipulate the group (e.g. add/remove it) as one layer. - */ - -L.LayerGroup = L.Class.extend({ - initialize: function (layers) { - this._layers = {}; - - var i, len; - - if (layers) { - for (i = 0, len = layers.length; i < len; i++) { - this.addLayer(layers[i]); - } - } - }, - - addLayer: function (layer) { - var id = this.getLayerId(layer); - - this._layers[id] = layer; - - if (this._map) { - this._map.addLayer(layer); - } - - return this; - }, - - removeLayer: function (layer) { - var id = layer in this._layers ? layer : this.getLayerId(layer); - - if (this._map && this._layers[id]) { - this._map.removeLayer(this._layers[id]); - } - - delete this._layers[id]; - - return this; - }, - - hasLayer: function (layer) { - if (!layer) { return false; } - - return (layer in this._layers || this.getLayerId(layer) in this._layers); - }, - - clearLayers: function () { - this.eachLayer(this.removeLayer, this); - return this; - }, - - invoke: function (methodName) { - var args = Array.prototype.slice.call(arguments, 1), - i, layer; - - for (i in this._layers) { - layer = this._layers[i]; - - if (layer[methodName]) { - layer[methodName].apply(layer, args); - } - } - - return this; - }, - - onAdd: function (map) { - this._map = map; - this.eachLayer(map.addLayer, map); - }, - - onRemove: function (map) { - this.eachLayer(map.removeLayer, map); - this._map = null; - }, - - addTo: function (map) { - map.addLayer(this); - return this; - }, - - eachLayer: function (method, context) { - for (var i in this._layers) { - method.call(context, this._layers[i]); - } - return this; - }, - - getLayer: function (id) { - return this._layers[id]; - }, - - getLayers: function () { - var layers = []; - - for (var i in this._layers) { - layers.push(this._layers[i]); - } - return layers; - }, - - setZIndex: function (zIndex) { - return this.invoke('setZIndex', zIndex); - }, - - getLayerId: function (layer) { - return L.stamp(layer); - } -}); - -L.layerGroup = function (layers) { - return new L.LayerGroup(layers); -}; - - -/* - * L.FeatureGroup extends L.LayerGroup by introducing mouse events and additional methods - * shared between a group of interactive layers (like vectors or markers). - */ - -L.FeatureGroup = L.LayerGroup.extend({ - includes: L.Mixin.Events, - - statics: { - EVENTS: 'click dblclick mouseover mouseout mousemove contextmenu popupopen popupclose' - }, - - addLayer: function (layer) { - if (this.hasLayer(layer)) { - return this; - } - - if ('on' in layer) { - layer.on(L.FeatureGroup.EVENTS, this._propagateEvent, this); - } - - L.LayerGroup.prototype.addLayer.call(this, layer); - - if (this._popupContent && layer.bindPopup) { - layer.bindPopup(this._popupContent, this._popupOptions); - } - - return this.fire('layeradd', {layer: layer}); - }, - - removeLayer: function (layer) { - if (!this.hasLayer(layer)) { - return this; - } - if (layer in this._layers) { - layer = this._layers[layer]; - } - - if ('off' in layer) { - layer.off(L.FeatureGroup.EVENTS, this._propagateEvent, this); - } - - L.LayerGroup.prototype.removeLayer.call(this, layer); - - if (this._popupContent) { - this.invoke('unbindPopup'); - } - - return this.fire('layerremove', {layer: layer}); - }, - - bindPopup: function (content, options) { - this._popupContent = content; - this._popupOptions = options; - return this.invoke('bindPopup', content, options); - }, - - openPopup: function (latlng) { - // open popup on the first layer - for (var id in this._layers) { - this._layers[id].openPopup(latlng); - break; - } - return this; - }, - - setStyle: function (style) { - return this.invoke('setStyle', style); - }, - - bringToFront: function () { - return this.invoke('bringToFront'); - }, - - bringToBack: function () { - return this.invoke('bringToBack'); - }, - - getBounds: function () { - var bounds = new L.LatLngBounds(); - - this.eachLayer(function (layer) { - bounds.extend(layer instanceof L.Marker ? layer.getLatLng() : layer.getBounds()); - }); - - return bounds; - }, - - _propagateEvent: function (e) { - e = L.extend({ - layer: e.target, - target: this - }, e); - this.fire(e.type, e); - } -}); - -L.featureGroup = function (layers) { - return new L.FeatureGroup(layers); -}; - - -/* - * L.Path is a base class for rendering vector paths on a map. Inherited by Polyline, Circle, etc. - */ - -L.Path = L.Class.extend({ - includes: [L.Mixin.Events], - - statics: { - // how much to extend the clip area around the map view - // (relative to its size, e.g. 0.5 is half the screen in each direction) - // set it so that SVG element doesn't exceed 1280px (vectors flicker on dragend if it is) - CLIP_PADDING: (function () { - var max = L.Browser.mobile ? 1280 : 2000, - target = (max / Math.max(window.outerWidth, window.outerHeight) - 1) / 2; - return Math.max(0, Math.min(0.5, target)); - })() - }, - - options: { - stroke: true, - color: '#0033ff', - dashArray: null, - lineCap: null, - lineJoin: null, - weight: 5, - opacity: 0.5, - - fill: false, - fillColor: null, //same as color by default - fillOpacity: 0.2, - - clickable: true - }, - - initialize: function (options) { - L.setOptions(this, options); - }, - - onAdd: function (map) { - this._map = map; - - if (!this._container) { - this._initElements(); - this._initEvents(); - } - - this.projectLatlngs(); - this._updatePath(); - - if (this._container) { - this._map._pathRoot.appendChild(this._container); - } - - this.fire('add'); - - map.on({ - 'viewreset': this.projectLatlngs, - 'moveend': this._updatePath - }, this); - }, - - addTo: function (map) { - map.addLayer(this); - return this; - }, - - onRemove: function (map) { - map._pathRoot.removeChild(this._container); - - // Need to fire remove event before we set _map to null as the event hooks might need the object - this.fire('remove'); - this._map = null; - - if (L.Browser.vml) { - this._container = null; - this._stroke = null; - this._fill = null; - } - - map.off({ - 'viewreset': this.projectLatlngs, - 'moveend': this._updatePath - }, this); - }, - - projectLatlngs: function () { - // do all projection stuff here - }, - - setStyle: function (style) { - L.setOptions(this, style); - - if (this._container) { - this._updateStyle(); - } - - return this; - }, - - redraw: function () { - if (this._map) { - this.projectLatlngs(); - this._updatePath(); - } - return this; - } -}); - -L.Map.include({ - _updatePathViewport: function () { - var p = L.Path.CLIP_PADDING, - size = this.getSize(), - panePos = L.DomUtil.getPosition(this._mapPane), - min = panePos.multiplyBy(-1)._subtract(size.multiplyBy(p)._round()), - max = min.add(size.multiplyBy(1 + p * 2)._round()); - - this._pathViewport = new L.Bounds(min, max); - } -}); - - -/* - * Extends L.Path with SVG-specific rendering code. - */ - -L.Path.SVG_NS = 'http://www.w3.org/2000/svg'; - -L.Browser.svg = !!(document.createElementNS && document.createElementNS(L.Path.SVG_NS, 'svg').createSVGRect); - -L.Path = L.Path.extend({ - statics: { - SVG: L.Browser.svg - }, - - bringToFront: function () { - var root = this._map._pathRoot, - path = this._container; - - if (path && root.lastChild !== path) { - root.appendChild(path); - } - return this; - }, - - bringToBack: function () { - var root = this._map._pathRoot, - path = this._container, - first = root.firstChild; - - if (path && first !== path) { - root.insertBefore(path, first); - } - return this; - }, - - getPathString: function () { - // form path string here - }, - - _createElement: function (name) { - return document.createElementNS(L.Path.SVG_NS, name); - }, - - _initElements: function () { - this._map._initPathRoot(); - this._initPath(); - this._initStyle(); - }, - - _initPath: function () { - this._container = this._createElement('g'); - - this._path = this._createElement('path'); - - if (this.options.className) { - L.DomUtil.addClass(this._path, this.options.className); - } - - this._container.appendChild(this._path); - }, - - _initStyle: function () { - if (this.options.stroke) { - this._path.setAttribute('stroke-linejoin', 'round'); - this._path.setAttribute('stroke-linecap', 'round'); - } - if (this.options.fill) { - this._path.setAttribute('fill-rule', 'evenodd'); - } - if (this.options.pointerEvents) { - this._path.setAttribute('pointer-events', this.options.pointerEvents); - } - if (!this.options.clickable && !this.options.pointerEvents) { - this._path.setAttribute('pointer-events', 'none'); - } - this._updateStyle(); - }, - - _updateStyle: function () { - if (this.options.stroke) { - this._path.setAttribute('stroke', this.options.color); - this._path.setAttribute('stroke-opacity', this.options.opacity); - this._path.setAttribute('stroke-width', this.options.weight); - if (this.options.dashArray) { - this._path.setAttribute('stroke-dasharray', this.options.dashArray); - } else { - this._path.removeAttribute('stroke-dasharray'); - } - if (this.options.lineCap) { - this._path.setAttribute('stroke-linecap', this.options.lineCap); - } - if (this.options.lineJoin) { - this._path.setAttribute('stroke-linejoin', this.options.lineJoin); - } - } else { - this._path.setAttribute('stroke', 'none'); - } - if (this.options.fill) { - this._path.setAttribute('fill', this.options.fillColor || this.options.color); - this._path.setAttribute('fill-opacity', this.options.fillOpacity); - } else { - this._path.setAttribute('fill', 'none'); - } - }, - - _updatePath: function () { - var str = this.getPathString(); - if (!str) { - // fix webkit empty string parsing bug - str = 'M0 0'; - } - this._path.setAttribute('d', str); - }, - - // TODO remove duplication with L.Map - _initEvents: function () { - if (this.options.clickable) { - if (L.Browser.svg || !L.Browser.vml) { - L.DomUtil.addClass(this._path, 'leaflet-clickable'); - } - - L.DomEvent.on(this._container, 'click', this._onMouseClick, this); - - var events = ['dblclick', 'mousedown', 'mouseover', - 'mouseout', 'mousemove', 'contextmenu']; - for (var i = 0; i < events.length; i++) { - L.DomEvent.on(this._container, events[i], this._fireMouseEvent, this); - } - } - }, - - _onMouseClick: function (e) { - if (this._map.dragging && this._map.dragging.moved()) { return; } - - this._fireMouseEvent(e); - }, - - _fireMouseEvent: function (e) { - if (!this._map || !this.hasEventListeners(e.type)) { return; } - - var map = this._map, - containerPoint = map.mouseEventToContainerPoint(e), - layerPoint = map.containerPointToLayerPoint(containerPoint), - latlng = map.layerPointToLatLng(layerPoint); - - this.fire(e.type, { - latlng: latlng, - layerPoint: layerPoint, - containerPoint: containerPoint, - originalEvent: e - }); - - if (e.type === 'contextmenu') { - L.DomEvent.preventDefault(e); - } - if (e.type !== 'mousemove') { - L.DomEvent.stopPropagation(e); - } - } -}); - -L.Map.include({ - _initPathRoot: function () { - if (!this._pathRoot) { - this._pathRoot = L.Path.prototype._createElement('svg'); - this._panes.overlayPane.appendChild(this._pathRoot); - - if (this.options.zoomAnimation && L.Browser.any3d) { - L.DomUtil.addClass(this._pathRoot, 'leaflet-zoom-animated'); - - this.on({ - 'zoomanim': this._animatePathZoom, - 'zoomend': this._endPathZoom - }); - } else { - L.DomUtil.addClass(this._pathRoot, 'leaflet-zoom-hide'); - } - - this.on('moveend', this._updateSvgViewport); - this._updateSvgViewport(); - } - }, - - _animatePathZoom: function (e) { - var scale = this.getZoomScale(e.zoom), - offset = this._getCenterOffset(e.center)._multiplyBy(-scale)._add(this._pathViewport.min); - - this._pathRoot.style[L.DomUtil.TRANSFORM] = - L.DomUtil.getTranslateString(offset) + ' scale(' + scale + ') '; - - this._pathZooming = true; - }, - - _endPathZoom: function () { - this._pathZooming = false; - }, - - _updateSvgViewport: function () { - - if (this._pathZooming) { - // Do not update SVGs while a zoom animation is going on otherwise the animation will break. - // When the zoom animation ends we will be updated again anyway - // This fixes the case where you do a momentum move and zoom while the move is still ongoing. - return; - } - - this._updatePathViewport(); - - var vp = this._pathViewport, - min = vp.min, - max = vp.max, - width = max.x - min.x, - height = max.y - min.y, - root = this._pathRoot, - pane = this._panes.overlayPane; - - // Hack to make flicker on drag end on mobile webkit less irritating - if (L.Browser.mobileWebkit) { - pane.removeChild(root); - } - - L.DomUtil.setPosition(root, min); - root.setAttribute('width', width); - root.setAttribute('height', height); - root.setAttribute('viewBox', [min.x, min.y, width, height].join(' ')); - - if (L.Browser.mobileWebkit) { - pane.appendChild(root); - } - } -}); - - -/* - * Popup extension to L.Path (polylines, polygons, circles), adding popup-related methods. - */ - -L.Path.include({ - - bindPopup: function (content, options) { - - if (content instanceof L.Popup) { - this._popup = content; - } else { - if (!this._popup || options) { - this._popup = new L.Popup(options, this); - } - this._popup.setContent(content); - } - - if (!this._popupHandlersAdded) { - this - .on('click', this._openPopup, this) - .on('remove', this.closePopup, this); - - this._popupHandlersAdded = true; - } - - return this; - }, - - unbindPopup: function () { - if (this._popup) { - this._popup = null; - this - .off('click', this._openPopup) - .off('remove', this.closePopup); - - this._popupHandlersAdded = false; - } - return this; - }, - - openPopup: function (latlng) { - - if (this._popup) { - // open the popup from one of the path's points if not specified - latlng = latlng || this._latlng || - this._latlngs[Math.floor(this._latlngs.length / 2)]; - - this._openPopup({latlng: latlng}); - } - - return this; - }, - - closePopup: function () { - if (this._popup) { - this._popup._close(); - } - return this; - }, - - _openPopup: function (e) { - this._popup.setLatLng(e.latlng); - this._map.openPopup(this._popup); - } -}); - - -/* - * Vector rendering for IE6-8 through VML. - * Thanks to Dmitry Baranovsky and his Raphael library for inspiration! - */ - -L.Browser.vml = !L.Browser.svg && (function () { - try { - var div = document.createElement('div'); - div.innerHTML = ''; - - var shape = div.firstChild; - shape.style.behavior = 'url(#default#VML)'; - - return shape && (typeof shape.adj === 'object'); - - } catch (e) { - return false; - } -}()); - -L.Path = L.Browser.svg || !L.Browser.vml ? L.Path : L.Path.extend({ - statics: { - VML: true, - CLIP_PADDING: 0.02 - }, - - _createElement: (function () { - try { - document.namespaces.add('lvml', 'urn:schemas-microsoft-com:vml'); - return function (name) { - return document.createElement(''); - }; - } catch (e) { - return function (name) { - return document.createElement( - '<' + name + ' xmlns="urn:schemas-microsoft.com:vml" class="lvml">'); - }; - } - }()), - - _initPath: function () { - var container = this._container = this._createElement('shape'); - - L.DomUtil.addClass(container, 'leaflet-vml-shape' + - (this.options.className ? ' ' + this.options.className : '')); - - if (this.options.clickable) { - L.DomUtil.addClass(container, 'leaflet-clickable'); - } - - container.coordsize = '1 1'; - - this._path = this._createElement('path'); - container.appendChild(this._path); - - this._map._pathRoot.appendChild(container); - }, - - _initStyle: function () { - this._updateStyle(); - }, - - _updateStyle: function () { - var stroke = this._stroke, - fill = this._fill, - options = this.options, - container = this._container; - - container.stroked = options.stroke; - container.filled = options.fill; - - if (options.stroke) { - if (!stroke) { - stroke = this._stroke = this._createElement('stroke'); - stroke.endcap = 'round'; - container.appendChild(stroke); - } - stroke.weight = options.weight + 'px'; - stroke.color = options.color; - stroke.opacity = options.opacity; - - if (options.dashArray) { - stroke.dashStyle = L.Util.isArray(options.dashArray) ? - options.dashArray.join(' ') : - options.dashArray.replace(/( *, *)/g, ' '); - } else { - stroke.dashStyle = ''; - } - if (options.lineCap) { - stroke.endcap = options.lineCap.replace('butt', 'flat'); - } - if (options.lineJoin) { - stroke.joinstyle = options.lineJoin; - } - - } else if (stroke) { - container.removeChild(stroke); - this._stroke = null; - } - - if (options.fill) { - if (!fill) { - fill = this._fill = this._createElement('fill'); - container.appendChild(fill); - } - fill.color = options.fillColor || options.color; - fill.opacity = options.fillOpacity; - - } else if (fill) { - container.removeChild(fill); - this._fill = null; - } - }, - - _updatePath: function () { - var style = this._container.style; - - style.display = 'none'; - this._path.v = this.getPathString() + ' '; // the space fixes IE empty path string bug - style.display = ''; - } -}); - -L.Map.include(L.Browser.svg || !L.Browser.vml ? {} : { - _initPathRoot: function () { - if (this._pathRoot) { return; } - - var root = this._pathRoot = document.createElement('div'); - root.className = 'leaflet-vml-container'; - this._panes.overlayPane.appendChild(root); - - this.on('moveend', this._updatePathViewport); - this._updatePathViewport(); - } -}); - - -/* - * Vector rendering for all browsers that support canvas. - */ - -L.Browser.canvas = (function () { - return !!document.createElement('canvas').getContext; -}()); - -L.Path = (L.Path.SVG && !window.L_PREFER_CANVAS) || !L.Browser.canvas ? L.Path : L.Path.extend({ - statics: { - //CLIP_PADDING: 0.02, // not sure if there's a need to set it to a small value - CANVAS: true, - SVG: false - }, - - redraw: function () { - if (this._map) { - this.projectLatlngs(); - this._requestUpdate(); - } - return this; - }, - - setStyle: function (style) { - L.setOptions(this, style); - - if (this._map) { - this._updateStyle(); - this._requestUpdate(); - } - return this; - }, - - onRemove: function (map) { - map - .off('viewreset', this.projectLatlngs, this) - .off('moveend', this._updatePath, this); - - if (this.options.clickable) { - this._map.off('click', this._onClick, this); - this._map.off('mousemove', this._onMouseMove, this); - } - - this._requestUpdate(); - - this.fire('remove'); - this._map = null; - }, - - _requestUpdate: function () { - if (this._map && !L.Path._updateRequest) { - L.Path._updateRequest = L.Util.requestAnimFrame(this._fireMapMoveEnd, this._map); - } - }, - - _fireMapMoveEnd: function () { - L.Path._updateRequest = null; - this.fire('moveend'); - }, - - _initElements: function () { - this._map._initPathRoot(); - this._ctx = this._map._canvasCtx; - }, - - _updateStyle: function () { - var options = this.options; - - if (options.stroke) { - this._ctx.lineWidth = options.weight; - this._ctx.strokeStyle = options.color; - } - if (options.fill) { - this._ctx.fillStyle = options.fillColor || options.color; - } - - if (options.lineCap) { - this._ctx.lineCap = options.lineCap; - } - if (options.lineJoin) { - this._ctx.lineJoin = options.lineJoin; - } - }, - - _drawPath: function () { - var i, j, len, len2, point, drawMethod; - - this._ctx.beginPath(); - - for (i = 0, len = this._parts.length; i < len; i++) { - for (j = 0, len2 = this._parts[i].length; j < len2; j++) { - point = this._parts[i][j]; - drawMethod = (j === 0 ? 'move' : 'line') + 'To'; - - this._ctx[drawMethod](point.x, point.y); - } - // TODO refactor ugly hack - if (this instanceof L.Polygon) { - this._ctx.closePath(); - } - } - }, - - _checkIfEmpty: function () { - return !this._parts.length; - }, - - _updatePath: function () { - if (this._checkIfEmpty()) { return; } - - var ctx = this._ctx, - options = this.options; - - this._drawPath(); - ctx.save(); - this._updateStyle(); - - if (options.fill) { - ctx.globalAlpha = options.fillOpacity; - ctx.fill(options.fillRule || 'evenodd'); - } - - if (options.stroke) { - ctx.globalAlpha = options.opacity; - ctx.stroke(); - } - - ctx.restore(); - - // TODO optimization: 1 fill/stroke for all features with equal style instead of 1 for each feature - }, - - _initEvents: function () { - if (this.options.clickable) { - this._map.on('mousemove', this._onMouseMove, this); - this._map.on('click dblclick contextmenu', this._fireMouseEvent, this); - } - }, - - _fireMouseEvent: function (e) { - if (this._containsPoint(e.layerPoint)) { - this.fire(e.type, e); - } - }, - - _onMouseMove: function (e) { - if (!this._map || this._map._animatingZoom) { return; } - - // TODO don't do on each move - if (this._containsPoint(e.layerPoint)) { - this._ctx.canvas.style.cursor = 'pointer'; - this._mouseInside = true; - this.fire('mouseover', e); - - } else if (this._mouseInside) { - this._ctx.canvas.style.cursor = ''; - this._mouseInside = false; - this.fire('mouseout', e); - } - } -}); - -L.Map.include((L.Path.SVG && !window.L_PREFER_CANVAS) || !L.Browser.canvas ? {} : { - _initPathRoot: function () { - var root = this._pathRoot, - ctx; - - if (!root) { - root = this._pathRoot = document.createElement('canvas'); - root.style.position = 'absolute'; - ctx = this._canvasCtx = root.getContext('2d'); - - ctx.lineCap = 'round'; - ctx.lineJoin = 'round'; - - this._panes.overlayPane.appendChild(root); - - if (this.options.zoomAnimation) { - this._pathRoot.className = 'leaflet-zoom-animated'; - this.on('zoomanim', this._animatePathZoom); - this.on('zoomend', this._endPathZoom); - } - this.on('moveend', this._updateCanvasViewport); - this._updateCanvasViewport(); - } - }, - - _updateCanvasViewport: function () { - // don't redraw while zooming. See _updateSvgViewport for more details - if (this._pathZooming) { return; } - this._updatePathViewport(); - - var vp = this._pathViewport, - min = vp.min, - size = vp.max.subtract(min), - root = this._pathRoot; - - //TODO check if this works properly on mobile webkit - L.DomUtil.setPosition(root, min); - root.width = size.x; - root.height = size.y; - root.getContext('2d').translate(-min.x, -min.y); - } -}); - - -/* - * L.LineUtil contains different utility functions for line segments - * and polylines (clipping, simplification, distances, etc.) - */ - -/*jshint bitwise:false */ // allow bitwise operations for this file - -L.LineUtil = { - - // Simplify polyline with vertex reduction and Douglas-Peucker simplification. - // Improves rendering performance dramatically by lessening the number of points to draw. - - simplify: function (/*Point[]*/ points, /*Number*/ tolerance) { - if (!tolerance || !points.length) { - return points.slice(); - } - - var sqTolerance = tolerance * tolerance; - - // stage 1: vertex reduction - points = this._reducePoints(points, sqTolerance); - - // stage 2: Douglas-Peucker simplification - points = this._simplifyDP(points, sqTolerance); - - return points; - }, - - // distance from a point to a segment between two points - pointToSegmentDistance: function (/*Point*/ p, /*Point*/ p1, /*Point*/ p2) { - return Math.sqrt(this._sqClosestPointOnSegment(p, p1, p2, true)); - }, - - closestPointOnSegment: function (/*Point*/ p, /*Point*/ p1, /*Point*/ p2) { - return this._sqClosestPointOnSegment(p, p1, p2); - }, - - // Douglas-Peucker simplification, see http://en.wikipedia.org/wiki/Douglas-Peucker_algorithm - _simplifyDP: function (points, sqTolerance) { - - var len = points.length, - ArrayConstructor = typeof Uint8Array !== undefined + '' ? Uint8Array : Array, - markers = new ArrayConstructor(len); - - markers[0] = markers[len - 1] = 1; - - this._simplifyDPStep(points, markers, sqTolerance, 0, len - 1); - - var i, - newPoints = []; - - for (i = 0; i < len; i++) { - if (markers[i]) { - newPoints.push(points[i]); - } - } - - return newPoints; - }, - - _simplifyDPStep: function (points, markers, sqTolerance, first, last) { - - var maxSqDist = 0, - index, i, sqDist; - - for (i = first + 1; i <= last - 1; i++) { - sqDist = this._sqClosestPointOnSegment(points[i], points[first], points[last], true); - - if (sqDist > maxSqDist) { - index = i; - maxSqDist = sqDist; - } - } - - if (maxSqDist > sqTolerance) { - markers[index] = 1; - - this._simplifyDPStep(points, markers, sqTolerance, first, index); - this._simplifyDPStep(points, markers, sqTolerance, index, last); - } - }, - - // reduce points that are too close to each other to a single point - _reducePoints: function (points, sqTolerance) { - var reducedPoints = [points[0]]; - - for (var i = 1, prev = 0, len = points.length; i < len; i++) { - if (this._sqDist(points[i], points[prev]) > sqTolerance) { - reducedPoints.push(points[i]); - prev = i; - } - } - if (prev < len - 1) { - reducedPoints.push(points[len - 1]); - } - return reducedPoints; - }, - - // Cohen-Sutherland line clipping algorithm. - // Used to avoid rendering parts of a polyline that are not currently visible. - - clipSegment: function (a, b, bounds, useLastCode) { - var codeA = useLastCode ? this._lastCode : this._getBitCode(a, bounds), - codeB = this._getBitCode(b, bounds), - - codeOut, p, newCode; - - // save 2nd code to avoid calculating it on the next segment - this._lastCode = codeB; - - while (true) { - // if a,b is inside the clip window (trivial accept) - if (!(codeA | codeB)) { - return [a, b]; - // if a,b is outside the clip window (trivial reject) - } else if (codeA & codeB) { - return false; - // other cases - } else { - codeOut = codeA || codeB; - p = this._getEdgeIntersection(a, b, codeOut, bounds); - newCode = this._getBitCode(p, bounds); - - if (codeOut === codeA) { - a = p; - codeA = newCode; - } else { - b = p; - codeB = newCode; - } - } - } - }, - - _getEdgeIntersection: function (a, b, code, bounds) { - var dx = b.x - a.x, - dy = b.y - a.y, - min = bounds.min, - max = bounds.max; - - if (code & 8) { // top - return new L.Point(a.x + dx * (max.y - a.y) / dy, max.y); - } else if (code & 4) { // bottom - return new L.Point(a.x + dx * (min.y - a.y) / dy, min.y); - } else if (code & 2) { // right - return new L.Point(max.x, a.y + dy * (max.x - a.x) / dx); - } else if (code & 1) { // left - return new L.Point(min.x, a.y + dy * (min.x - a.x) / dx); - } - }, - - _getBitCode: function (/*Point*/ p, bounds) { - var code = 0; - - if (p.x < bounds.min.x) { // left - code |= 1; - } else if (p.x > bounds.max.x) { // right - code |= 2; - } - if (p.y < bounds.min.y) { // bottom - code |= 4; - } else if (p.y > bounds.max.y) { // top - code |= 8; - } - - return code; - }, - - // square distance (to avoid unnecessary Math.sqrt calls) - _sqDist: function (p1, p2) { - var dx = p2.x - p1.x, - dy = p2.y - p1.y; - return dx * dx + dy * dy; - }, - - // return closest point on segment or distance to that point - _sqClosestPointOnSegment: function (p, p1, p2, sqDist) { - var x = p1.x, - y = p1.y, - dx = p2.x - x, - dy = p2.y - y, - dot = dx * dx + dy * dy, - t; - - if (dot > 0) { - t = ((p.x - x) * dx + (p.y - y) * dy) / dot; - - if (t > 1) { - x = p2.x; - y = p2.y; - } else if (t > 0) { - x += dx * t; - y += dy * t; - } - } - - dx = p.x - x; - dy = p.y - y; - - return sqDist ? dx * dx + dy * dy : new L.Point(x, y); - } -}; - - -/* - * L.Polyline is used to display polylines on a map. - */ - -L.Polyline = L.Path.extend({ - initialize: function (latlngs, options) { - L.Path.prototype.initialize.call(this, options); - - this._latlngs = this._convertLatLngs(latlngs); - }, - - options: { - // how much to simplify the polyline on each zoom level - // more = better performance and smoother look, less = more accurate - smoothFactor: 1.0, - noClip: false - }, - - projectLatlngs: function () { - this._originalPoints = []; - - for (var i = 0, len = this._latlngs.length; i < len; i++) { - this._originalPoints[i] = this._map.latLngToLayerPoint(this._latlngs[i]); - } - }, - - getPathString: function () { - for (var i = 0, len = this._parts.length, str = ''; i < len; i++) { - str += this._getPathPartStr(this._parts[i]); - } - return str; - }, - - getLatLngs: function () { - return this._latlngs; - }, - - setLatLngs: function (latlngs) { - this._latlngs = this._convertLatLngs(latlngs); - return this.redraw(); - }, - - addLatLng: function (latlng) { - this._latlngs.push(L.latLng(latlng)); - return this.redraw(); - }, - - spliceLatLngs: function () { // (Number index, Number howMany) - var removed = [].splice.apply(this._latlngs, arguments); - this._convertLatLngs(this._latlngs, true); - this.redraw(); - return removed; - }, - - closestLayerPoint: function (p) { - var minDistance = Infinity, parts = this._parts, p1, p2, minPoint = null; - - for (var j = 0, jLen = parts.length; j < jLen; j++) { - var points = parts[j]; - for (var i = 1, len = points.length; i < len; i++) { - p1 = points[i - 1]; - p2 = points[i]; - var sqDist = L.LineUtil._sqClosestPointOnSegment(p, p1, p2, true); - if (sqDist < minDistance) { - minDistance = sqDist; - minPoint = L.LineUtil._sqClosestPointOnSegment(p, p1, p2); - } - } - } - if (minPoint) { - minPoint.distance = Math.sqrt(minDistance); - } - return minPoint; - }, - - getBounds: function () { - return new L.LatLngBounds(this.getLatLngs()); - }, - - _convertLatLngs: function (latlngs, overwrite) { - var i, len, target = overwrite ? latlngs : []; - - for (i = 0, len = latlngs.length; i < len; i++) { - if (L.Util.isArray(latlngs[i]) && typeof latlngs[i][0] !== 'number') { - return; - } - target[i] = L.latLng(latlngs[i]); - } - return target; - }, - - _initEvents: function () { - L.Path.prototype._initEvents.call(this); - }, - - _getPathPartStr: function (points) { - var round = L.Path.VML; - - for (var j = 0, len2 = points.length, str = '', p; j < len2; j++) { - p = points[j]; - if (round) { - p._round(); - } - str += (j ? 'L' : 'M') + p.x + ' ' + p.y; - } - return str; - }, - - _clipPoints: function () { - var points = this._originalPoints, - len = points.length, - i, k, segment; - - if (this.options.noClip) { - this._parts = [points]; - return; - } - - this._parts = []; - - var parts = this._parts, - vp = this._map._pathViewport, - lu = L.LineUtil; - - for (i = 0, k = 0; i < len - 1; i++) { - segment = lu.clipSegment(points[i], points[i + 1], vp, i); - if (!segment) { - continue; - } - - parts[k] = parts[k] || []; - parts[k].push(segment[0]); - - // if segment goes out of screen, or it's the last one, it's the end of the line part - if ((segment[1] !== points[i + 1]) || (i === len - 2)) { - parts[k].push(segment[1]); - k++; - } - } - }, - - // simplify each clipped part of the polyline - _simplifyPoints: function () { - var parts = this._parts, - lu = L.LineUtil; - - for (var i = 0, len = parts.length; i < len; i++) { - parts[i] = lu.simplify(parts[i], this.options.smoothFactor); - } - }, - - _updatePath: function () { - if (!this._map) { return; } - - this._clipPoints(); - this._simplifyPoints(); - - L.Path.prototype._updatePath.call(this); - } -}); - -L.polyline = function (latlngs, options) { - return new L.Polyline(latlngs, options); -}; - - -/* - * L.PolyUtil contains utility functions for polygons (clipping, etc.). - */ - -/*jshint bitwise:false */ // allow bitwise operations here - -L.PolyUtil = {}; - -/* - * Sutherland-Hodgeman polygon clipping algorithm. - * Used to avoid rendering parts of a polygon that are not currently visible. - */ -L.PolyUtil.clipPolygon = function (points, bounds) { - var clippedPoints, - edges = [1, 4, 2, 8], - i, j, k, - a, b, - len, edge, p, - lu = L.LineUtil; - - for (i = 0, len = points.length; i < len; i++) { - points[i]._code = lu._getBitCode(points[i], bounds); - } - - // for each edge (left, bottom, right, top) - for (k = 0; k < 4; k++) { - edge = edges[k]; - clippedPoints = []; - - for (i = 0, len = points.length, j = len - 1; i < len; j = i++) { - a = points[i]; - b = points[j]; - - // if a is inside the clip window - if (!(a._code & edge)) { - // if b is outside the clip window (a->b goes out of screen) - if (b._code & edge) { - p = lu._getEdgeIntersection(b, a, edge, bounds); - p._code = lu._getBitCode(p, bounds); - clippedPoints.push(p); - } - clippedPoints.push(a); - - // else if b is inside the clip window (a->b enters the screen) - } else if (!(b._code & edge)) { - p = lu._getEdgeIntersection(b, a, edge, bounds); - p._code = lu._getBitCode(p, bounds); - clippedPoints.push(p); - } - } - points = clippedPoints; - } - - return points; -}; - - -/* - * L.Polygon is used to display polygons on a map. - */ - -L.Polygon = L.Polyline.extend({ - options: { - fill: true - }, - - initialize: function (latlngs, options) { - L.Polyline.prototype.initialize.call(this, latlngs, options); - this._initWithHoles(latlngs); - }, - - _initWithHoles: function (latlngs) { - var i, len, hole; - if (latlngs && L.Util.isArray(latlngs[0]) && (typeof latlngs[0][0] !== 'number')) { - this._latlngs = this._convertLatLngs(latlngs[0]); - this._holes = latlngs.slice(1); - - for (i = 0, len = this._holes.length; i < len; i++) { - hole = this._holes[i] = this._convertLatLngs(this._holes[i]); - if (hole[0].equals(hole[hole.length - 1])) { - hole.pop(); - } - } - } - - // filter out last point if its equal to the first one - latlngs = this._latlngs; - - if (latlngs.length >= 2 && latlngs[0].equals(latlngs[latlngs.length - 1])) { - latlngs.pop(); - } - }, - - projectLatlngs: function () { - L.Polyline.prototype.projectLatlngs.call(this); - - // project polygon holes points - // TODO move this logic to Polyline to get rid of duplication - this._holePoints = []; - - if (!this._holes) { return; } - - var i, j, len, len2; - - for (i = 0, len = this._holes.length; i < len; i++) { - this._holePoints[i] = []; - - for (j = 0, len2 = this._holes[i].length; j < len2; j++) { - this._holePoints[i][j] = this._map.latLngToLayerPoint(this._holes[i][j]); - } - } - }, - - setLatLngs: function (latlngs) { - if (latlngs && L.Util.isArray(latlngs[0]) && (typeof latlngs[0][0] !== 'number')) { - this._initWithHoles(latlngs); - return this.redraw(); - } else { - return L.Polyline.prototype.setLatLngs.call(this, latlngs); - } - }, - - _clipPoints: function () { - var points = this._originalPoints, - newParts = []; - - this._parts = [points].concat(this._holePoints); - - if (this.options.noClip) { return; } - - for (var i = 0, len = this._parts.length; i < len; i++) { - var clipped = L.PolyUtil.clipPolygon(this._parts[i], this._map._pathViewport); - if (clipped.length) { - newParts.push(clipped); - } - } - - this._parts = newParts; - }, - - _getPathPartStr: function (points) { - var str = L.Polyline.prototype._getPathPartStr.call(this, points); - return str + (L.Browser.svg ? 'z' : 'x'); - } -}); - -L.polygon = function (latlngs, options) { - return new L.Polygon(latlngs, options); -}; - - -/* - * Contains L.MultiPolyline and L.MultiPolygon layers. - */ - -(function () { - function createMulti(Klass) { - - return L.FeatureGroup.extend({ - - initialize: function (latlngs, options) { - this._layers = {}; - this._options = options; - this.setLatLngs(latlngs); - }, - - setLatLngs: function (latlngs) { - var i = 0, - len = latlngs.length; - - this.eachLayer(function (layer) { - if (i < len) { - layer.setLatLngs(latlngs[i++]); - } else { - this.removeLayer(layer); - } - }, this); - - while (i < len) { - this.addLayer(new Klass(latlngs[i++], this._options)); - } - - return this; - }, - - getLatLngs: function () { - var latlngs = []; - - this.eachLayer(function (layer) { - latlngs.push(layer.getLatLngs()); - }); - - return latlngs; - } - }); - } - - L.MultiPolyline = createMulti(L.Polyline); - L.MultiPolygon = createMulti(L.Polygon); - - L.multiPolyline = function (latlngs, options) { - return new L.MultiPolyline(latlngs, options); - }; - - L.multiPolygon = function (latlngs, options) { - return new L.MultiPolygon(latlngs, options); - }; -}()); - - -/* - * L.Rectangle extends Polygon and creates a rectangle when passed a LatLngBounds object. - */ - -L.Rectangle = L.Polygon.extend({ - initialize: function (latLngBounds, options) { - L.Polygon.prototype.initialize.call(this, this._boundsToLatLngs(latLngBounds), options); - }, - - setBounds: function (latLngBounds) { - this.setLatLngs(this._boundsToLatLngs(latLngBounds)); - }, - - _boundsToLatLngs: function (latLngBounds) { - latLngBounds = L.latLngBounds(latLngBounds); - return [ - latLngBounds.getSouthWest(), - latLngBounds.getNorthWest(), - latLngBounds.getNorthEast(), - latLngBounds.getSouthEast() - ]; - } -}); - -L.rectangle = function (latLngBounds, options) { - return new L.Rectangle(latLngBounds, options); -}; - - -/* - * L.Circle is a circle overlay (with a certain radius in meters). - */ - -L.Circle = L.Path.extend({ - initialize: function (latlng, radius, options) { - L.Path.prototype.initialize.call(this, options); - - this._latlng = L.latLng(latlng); - this._mRadius = radius; - }, - - options: { - fill: true - }, - - setLatLng: function (latlng) { - this._latlng = L.latLng(latlng); - return this.redraw(); - }, - - setRadius: function (radius) { - this._mRadius = radius; - return this.redraw(); - }, - - projectLatlngs: function () { - var lngRadius = this._getLngRadius(), - latlng = this._latlng, - pointLeft = this._map.latLngToLayerPoint([latlng.lat, latlng.lng - lngRadius]); - - this._point = this._map.latLngToLayerPoint(latlng); - this._radius = Math.max(this._point.x - pointLeft.x, 1); - }, - - getBounds: function () { - var lngRadius = this._getLngRadius(), - latRadius = (this._mRadius / 40075017) * 360, - latlng = this._latlng; - - return new L.LatLngBounds( - [latlng.lat - latRadius, latlng.lng - lngRadius], - [latlng.lat + latRadius, latlng.lng + lngRadius]); - }, - - getLatLng: function () { - return this._latlng; - }, - - getPathString: function () { - var p = this._point, - r = this._radius; - - if (this._checkIfEmpty()) { - return ''; - } - - if (L.Browser.svg) { - return 'M' + p.x + ',' + (p.y - r) + - 'A' + r + ',' + r + ',0,1,1,' + - (p.x - 0.1) + ',' + (p.y - r) + ' z'; - } else { - p._round(); - r = Math.round(r); - return 'AL ' + p.x + ',' + p.y + ' ' + r + ',' + r + ' 0,' + (65535 * 360); - } - }, - - getRadius: function () { - return this._mRadius; - }, - - // TODO Earth hardcoded, move into projection code! - - _getLatRadius: function () { - return (this._mRadius / 40075017) * 360; - }, - - _getLngRadius: function () { - return this._getLatRadius() / Math.cos(L.LatLng.DEG_TO_RAD * this._latlng.lat); - }, - - _checkIfEmpty: function () { - if (!this._map) { - return false; - } - var vp = this._map._pathViewport, - r = this._radius, - p = this._point; - - return p.x - r > vp.max.x || p.y - r > vp.max.y || - p.x + r < vp.min.x || p.y + r < vp.min.y; - } -}); - -L.circle = function (latlng, radius, options) { - return new L.Circle(latlng, radius, options); -}; - - -/* - * L.CircleMarker is a circle overlay with a permanent pixel radius. - */ - -L.CircleMarker = L.Circle.extend({ - options: { - radius: 10, - weight: 2 - }, - - initialize: function (latlng, options) { - L.Circle.prototype.initialize.call(this, latlng, null, options); - this._radius = this.options.radius; - }, - - projectLatlngs: function () { - this._point = this._map.latLngToLayerPoint(this._latlng); - }, - - _updateStyle : function () { - L.Circle.prototype._updateStyle.call(this); - this.setRadius(this.options.radius); - }, - - setLatLng: function (latlng) { - L.Circle.prototype.setLatLng.call(this, latlng); - if (this._popup && this._popup._isOpen) { - this._popup.setLatLng(latlng); - } - return this; - }, - - setRadius: function (radius) { - this.options.radius = this._radius = radius; - return this.redraw(); - }, - - getRadius: function () { - return this._radius; - } -}); - -L.circleMarker = function (latlng, options) { - return new L.CircleMarker(latlng, options); -}; - - -/* - * Extends L.Polyline to be able to manually detect clicks on Canvas-rendered polylines. - */ - -L.Polyline.include(!L.Path.CANVAS ? {} : { - _containsPoint: function (p, closed) { - var i, j, k, len, len2, dist, part, - w = this.options.weight / 2; - - if (L.Browser.touch) { - w += 10; // polyline click tolerance on touch devices - } - - for (i = 0, len = this._parts.length; i < len; i++) { - part = this._parts[i]; - for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) { - if (!closed && (j === 0)) { - continue; - } - - dist = L.LineUtil.pointToSegmentDistance(p, part[k], part[j]); - - if (dist <= w) { - return true; - } - } - } - return false; - } -}); - - -/* - * Extends L.Polygon to be able to manually detect clicks on Canvas-rendered polygons. - */ - -L.Polygon.include(!L.Path.CANVAS ? {} : { - _containsPoint: function (p) { - var inside = false, - part, p1, p2, - i, j, k, - len, len2; - - // TODO optimization: check if within bounds first - - if (L.Polyline.prototype._containsPoint.call(this, p, true)) { - // click on polygon border - return true; - } - - // ray casting algorithm for detecting if point is in polygon - - for (i = 0, len = this._parts.length; i < len; i++) { - part = this._parts[i]; - - for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) { - p1 = part[j]; - p2 = part[k]; - - if (((p1.y > p.y) !== (p2.y > p.y)) && - (p.x < (p2.x - p1.x) * (p.y - p1.y) / (p2.y - p1.y) + p1.x)) { - inside = !inside; - } - } - } - - return inside; - } -}); - - -/* - * Extends L.Circle with Canvas-specific code. - */ - -L.Circle.include(!L.Path.CANVAS ? {} : { - _drawPath: function () { - var p = this._point; - this._ctx.beginPath(); - this._ctx.arc(p.x, p.y, this._radius, 0, Math.PI * 2, false); - }, - - _containsPoint: function (p) { - var center = this._point, - w2 = this.options.stroke ? this.options.weight / 2 : 0; - - return (p.distanceTo(center) <= this._radius + w2); - } -}); - - -/* - * CircleMarker canvas specific drawing parts. - */ - -L.CircleMarker.include(!L.Path.CANVAS ? {} : { - _updateStyle: function () { - L.Path.prototype._updateStyle.call(this); - } -}); - - -/* - * L.GeoJSON turns any GeoJSON data into a Leaflet layer. - */ - -L.GeoJSON = L.FeatureGroup.extend({ - - initialize: function (geojson, options) { - L.setOptions(this, options); - - this._layers = {}; - - if (geojson) { - this.addData(geojson); - } - }, - - addData: function (geojson) { - var features = L.Util.isArray(geojson) ? geojson : geojson.features, - i, len, feature; - - if (features) { - for (i = 0, len = features.length; i < len; i++) { - // Only add this if geometry or geometries are set and not null - feature = features[i]; - if (feature.geometries || feature.geometry || feature.features || feature.coordinates) { - this.addData(features[i]); - } - } - return this; - } - - var options = this.options; - - if (options.filter && !options.filter(geojson)) { return; } - - var layer = L.GeoJSON.geometryToLayer(geojson, options.pointToLayer, options.coordsToLatLng, options); - layer.feature = L.GeoJSON.asFeature(geojson); - - layer.defaultOptions = layer.options; - this.resetStyle(layer); - - if (options.onEachFeature) { - options.onEachFeature(geojson, layer); - } - - return this.addLayer(layer); - }, - - resetStyle: function (layer) { - var style = this.options.style; - if (style) { - // reset any custom styles - L.Util.extend(layer.options, layer.defaultOptions); - - this._setLayerStyle(layer, style); - } - }, - - setStyle: function (style) { - this.eachLayer(function (layer) { - this._setLayerStyle(layer, style); - }, this); - }, - - _setLayerStyle: function (layer, style) { - if (typeof style === 'function') { - style = style(layer.feature); - } - if (layer.setStyle) { - layer.setStyle(style); - } - } -}); - -L.extend(L.GeoJSON, { - geometryToLayer: function (geojson, pointToLayer, coordsToLatLng, vectorOptions) { - var geometry = geojson.type === 'Feature' ? geojson.geometry : geojson, - coords = geometry.coordinates, - layers = [], - latlng, latlngs, i, len; - - coordsToLatLng = coordsToLatLng || this.coordsToLatLng; - - switch (geometry.type) { - case 'Point': - latlng = coordsToLatLng(coords); - return pointToLayer ? pointToLayer(geojson, latlng) : new L.Marker(latlng); - - case 'MultiPoint': - for (i = 0, len = coords.length; i < len; i++) { - latlng = coordsToLatLng(coords[i]); - layers.push(pointToLayer ? pointToLayer(geojson, latlng) : new L.Marker(latlng)); - } - return new L.FeatureGroup(layers); - - case 'LineString': - latlngs = this.coordsToLatLngs(coords, 0, coordsToLatLng); - return new L.Polyline(latlngs, vectorOptions); - - case 'Polygon': - if (coords.length === 2 && !coords[1].length) { - throw new Error('Invalid GeoJSON object.'); - } - latlngs = this.coordsToLatLngs(coords, 1, coordsToLatLng); - return new L.Polygon(latlngs, vectorOptions); - - case 'MultiLineString': - latlngs = this.coordsToLatLngs(coords, 1, coordsToLatLng); - return new L.MultiPolyline(latlngs, vectorOptions); - - case 'MultiPolygon': - latlngs = this.coordsToLatLngs(coords, 2, coordsToLatLng); - return new L.MultiPolygon(latlngs, vectorOptions); - - case 'GeometryCollection': - for (i = 0, len = geometry.geometries.length; i < len; i++) { - - layers.push(this.geometryToLayer({ - geometry: geometry.geometries[i], - type: 'Feature', - properties: geojson.properties - }, pointToLayer, coordsToLatLng, vectorOptions)); - } - return new L.FeatureGroup(layers); - - default: - throw new Error('Invalid GeoJSON object.'); - } - }, - - coordsToLatLng: function (coords) { // (Array[, Boolean]) -> LatLng - return new L.LatLng(coords[1], coords[0], coords[2]); - }, - - coordsToLatLngs: function (coords, levelsDeep, coordsToLatLng) { // (Array[, Number, Function]) -> Array - var latlng, i, len, - latlngs = []; - - for (i = 0, len = coords.length; i < len; i++) { - latlng = levelsDeep ? - this.coordsToLatLngs(coords[i], levelsDeep - 1, coordsToLatLng) : - (coordsToLatLng || this.coordsToLatLng)(coords[i]); - - latlngs.push(latlng); - } - - return latlngs; - }, - - latLngToCoords: function (latlng) { - var coords = [latlng.lng, latlng.lat]; - - if (latlng.alt !== undefined) { - coords.push(latlng.alt); - } - return coords; - }, - - latLngsToCoords: function (latLngs) { - var coords = []; - - for (var i = 0, len = latLngs.length; i < len; i++) { - coords.push(L.GeoJSON.latLngToCoords(latLngs[i])); - } - - return coords; - }, - - getFeature: function (layer, newGeometry) { - return layer.feature ? L.extend({}, layer.feature, {geometry: newGeometry}) : L.GeoJSON.asFeature(newGeometry); - }, - - asFeature: function (geoJSON) { - if (geoJSON.type === 'Feature') { - return geoJSON; - } - - return { - type: 'Feature', - properties: {}, - geometry: geoJSON - }; - } -}); - -var PointToGeoJSON = { - toGeoJSON: function () { - return L.GeoJSON.getFeature(this, { - type: 'Point', - coordinates: L.GeoJSON.latLngToCoords(this.getLatLng()) - }); - } -}; - -L.Marker.include(PointToGeoJSON); -L.Circle.include(PointToGeoJSON); -L.CircleMarker.include(PointToGeoJSON); - -L.Polyline.include({ - toGeoJSON: function () { - return L.GeoJSON.getFeature(this, { - type: 'LineString', - coordinates: L.GeoJSON.latLngsToCoords(this.getLatLngs()) - }); - } -}); - -L.Polygon.include({ - toGeoJSON: function () { - var coords = [L.GeoJSON.latLngsToCoords(this.getLatLngs())], - i, len, hole; - - coords[0].push(coords[0][0]); - - if (this._holes) { - for (i = 0, len = this._holes.length; i < len; i++) { - hole = L.GeoJSON.latLngsToCoords(this._holes[i]); - hole.push(hole[0]); - coords.push(hole); - } - } - - return L.GeoJSON.getFeature(this, { - type: 'Polygon', - coordinates: coords - }); - } -}); - -(function () { - function multiToGeoJSON(type) { - return function () { - var coords = []; - - this.eachLayer(function (layer) { - coords.push(layer.toGeoJSON().geometry.coordinates); - }); - - return L.GeoJSON.getFeature(this, { - type: type, - coordinates: coords - }); - }; - } - - L.MultiPolyline.include({toGeoJSON: multiToGeoJSON('MultiLineString')}); - L.MultiPolygon.include({toGeoJSON: multiToGeoJSON('MultiPolygon')}); - - L.LayerGroup.include({ - toGeoJSON: function () { - - var geometry = this.feature && this.feature.geometry, - jsons = [], - json; - - if (geometry && geometry.type === 'MultiPoint') { - return multiToGeoJSON('MultiPoint').call(this); - } - - var isGeometryCollection = geometry && geometry.type === 'GeometryCollection'; - - this.eachLayer(function (layer) { - if (layer.toGeoJSON) { - json = layer.toGeoJSON(); - jsons.push(isGeometryCollection ? json.geometry : L.GeoJSON.asFeature(json)); - } - }); - - if (isGeometryCollection) { - return L.GeoJSON.getFeature(this, { - geometries: jsons, - type: 'GeometryCollection' - }); - } - - return { - type: 'FeatureCollection', - features: jsons - }; - } - }); -}()); - -L.geoJson = function (geojson, options) { - return new L.GeoJSON(geojson, options); -}; - - -/* - * L.DomEvent contains functions for working with DOM events. - */ - -L.DomEvent = { - /* inspired by John Resig, Dean Edwards and YUI addEvent implementations */ - addListener: function (obj, type, fn, context) { // (HTMLElement, String, Function[, Object]) - - var id = L.stamp(fn), - key = '_leaflet_' + type + id, - handler, originalHandler, newType; - - if (obj[key]) { return this; } - - handler = function (e) { - return fn.call(context || obj, e || L.DomEvent._getEvent()); - }; - - if (L.Browser.pointer && type.indexOf('touch') === 0) { - return this.addPointerListener(obj, type, handler, id); - } - if (L.Browser.touch && (type === 'dblclick') && this.addDoubleTapListener) { - this.addDoubleTapListener(obj, handler, id); - } - - if ('addEventListener' in obj) { - - if (type === 'mousewheel') { - obj.addEventListener('DOMMouseScroll', handler, false); - obj.addEventListener(type, handler, false); - - } else if ((type === 'mouseenter') || (type === 'mouseleave')) { - - originalHandler = handler; - newType = (type === 'mouseenter' ? 'mouseover' : 'mouseout'); - - handler = function (e) { - if (!L.DomEvent._checkMouse(obj, e)) { return; } - return originalHandler(e); - }; - - obj.addEventListener(newType, handler, false); - - } else if (type === 'click' && L.Browser.android) { - originalHandler = handler; - handler = function (e) { - return L.DomEvent._filterClick(e, originalHandler); - }; - - obj.addEventListener(type, handler, false); - } else { - obj.addEventListener(type, handler, false); - } - - } else if ('attachEvent' in obj) { - obj.attachEvent('on' + type, handler); - } - - obj[key] = handler; - - return this; - }, - - removeListener: function (obj, type, fn) { // (HTMLElement, String, Function) - - var id = L.stamp(fn), - key = '_leaflet_' + type + id, - handler = obj[key]; - - if (!handler) { return this; } - - if (L.Browser.pointer && type.indexOf('touch') === 0) { - this.removePointerListener(obj, type, id); - } else if (L.Browser.touch && (type === 'dblclick') && this.removeDoubleTapListener) { - this.removeDoubleTapListener(obj, id); - - } else if ('removeEventListener' in obj) { - - if (type === 'mousewheel') { - obj.removeEventListener('DOMMouseScroll', handler, false); - obj.removeEventListener(type, handler, false); - - } else if ((type === 'mouseenter') || (type === 'mouseleave')) { - obj.removeEventListener((type === 'mouseenter' ? 'mouseover' : 'mouseout'), handler, false); - } else { - obj.removeEventListener(type, handler, false); - } - } else if ('detachEvent' in obj) { - obj.detachEvent('on' + type, handler); - } - - obj[key] = null; - - return this; - }, - - stopPropagation: function (e) { - - if (e.stopPropagation) { - e.stopPropagation(); - } else { - e.cancelBubble = true; - } - L.DomEvent._skipped(e); - - return this; - }, - - disableScrollPropagation: function (el) { - var stop = L.DomEvent.stopPropagation; - - return L.DomEvent - .on(el, 'mousewheel', stop) - .on(el, 'MozMousePixelScroll', stop); - }, - - disableClickPropagation: function (el) { - var stop = L.DomEvent.stopPropagation; - - for (var i = L.Draggable.START.length - 1; i >= 0; i--) { - L.DomEvent.on(el, L.Draggable.START[i], stop); - } - - return L.DomEvent - .on(el, 'click', L.DomEvent._fakeStop) - .on(el, 'dblclick', stop); - }, - - preventDefault: function (e) { - - if (e.preventDefault) { - e.preventDefault(); - } else { - e.returnValue = false; - } - return this; - }, - - stop: function (e) { - return L.DomEvent - .preventDefault(e) - .stopPropagation(e); - }, - - getMousePosition: function (e, container) { - if (!container) { - return new L.Point(e.clientX, e.clientY); - } - - var rect = container.getBoundingClientRect(); - - return new L.Point( - e.clientX - rect.left - container.clientLeft, - e.clientY - rect.top - container.clientTop); - }, - - getWheelDelta: function (e) { - - var delta = 0; - - if (e.wheelDelta) { - delta = e.wheelDelta / 120; - } - if (e.detail) { - delta = -e.detail / 3; - } - return delta; - }, - - _skipEvents: {}, - - _fakeStop: function (e) { - // fakes stopPropagation by setting a special event flag, checked/reset with L.DomEvent._skipped(e) - L.DomEvent._skipEvents[e.type] = true; - }, - - _skipped: function (e) { - var skipped = this._skipEvents[e.type]; - // reset when checking, as it's only used in map container and propagates outside of the map - this._skipEvents[e.type] = false; - return skipped; - }, - - // check if element really left/entered the event target (for mouseenter/mouseleave) - _checkMouse: function (el, e) { - - var related = e.relatedTarget; - - if (!related) { return true; } - - try { - while (related && (related !== el)) { - related = related.parentNode; - } - } catch (err) { - return false; - } - return (related !== el); - }, - - _getEvent: function () { // evil magic for IE - /*jshint noarg:false */ - var e = window.event; - if (!e) { - var caller = arguments.callee.caller; - while (caller) { - e = caller['arguments'][0]; - if (e && window.Event === e.constructor) { - break; - } - caller = caller.caller; - } - } - return e; - }, - - // this is a horrible workaround for a bug in Android where a single touch triggers two click events - _filterClick: function (e, handler) { - var timeStamp = (e.timeStamp || e.originalEvent.timeStamp), - elapsed = L.DomEvent._lastClick && (timeStamp - L.DomEvent._lastClick); - - // are they closer together than 500ms yet more than 100ms? - // Android typically triggers them ~300ms apart while multiple listeners - // on the same event should be triggered far faster; - // or check if click is simulated on the element, and if it is, reject any non-simulated events - - if ((elapsed && elapsed > 100 && elapsed < 500) || (e.target._simulatedClick && !e._simulated)) { - L.DomEvent.stop(e); - return; - } - L.DomEvent._lastClick = timeStamp; - - return handler(e); - } -}; - -L.DomEvent.on = L.DomEvent.addListener; -L.DomEvent.off = L.DomEvent.removeListener; - - -/* - * L.Draggable allows you to add dragging capabilities to any element. Supports mobile devices too. - */ - -L.Draggable = L.Class.extend({ - includes: L.Mixin.Events, - - statics: { - START: L.Browser.touch ? ['touchstart', 'mousedown'] : ['mousedown'], - END: { - mousedown: 'mouseup', - touchstart: 'touchend', - pointerdown: 'touchend', - MSPointerDown: 'touchend' - }, - MOVE: { - mousedown: 'mousemove', - touchstart: 'touchmove', - pointerdown: 'touchmove', - MSPointerDown: 'touchmove' - } - }, - - initialize: function (element, dragStartTarget) { - this._element = element; - this._dragStartTarget = dragStartTarget || element; - }, - - enable: function () { - if (this._enabled) { return; } - - for (var i = L.Draggable.START.length - 1; i >= 0; i--) { - L.DomEvent.on(this._dragStartTarget, L.Draggable.START[i], this._onDown, this); - } - - this._enabled = true; - }, - - disable: function () { - if (!this._enabled) { return; } - - for (var i = L.Draggable.START.length - 1; i >= 0; i--) { - L.DomEvent.off(this._dragStartTarget, L.Draggable.START[i], this._onDown, this); - } - - this._enabled = false; - this._moved = false; - }, - - _onDown: function (e) { - this._moved = false; - - if (e.shiftKey || ((e.which !== 1) && (e.button !== 1) && !e.touches)) { return; } - - L.DomEvent.stopPropagation(e); - - if (L.Draggable._disabled) { return; } - - L.DomUtil.disableImageDrag(); - L.DomUtil.disableTextSelection(); - - if (this._moving) { return; } - - var first = e.touches ? e.touches[0] : e; - - this._startPoint = new L.Point(first.clientX, first.clientY); - this._startPos = this._newPos = L.DomUtil.getPosition(this._element); - - L.DomEvent - .on(document, L.Draggable.MOVE[e.type], this._onMove, this) - .on(document, L.Draggable.END[e.type], this._onUp, this); - }, - - _onMove: function (e) { - if (e.touches && e.touches.length > 1) { - this._moved = true; - return; - } - - var first = (e.touches && e.touches.length === 1 ? e.touches[0] : e), - newPoint = new L.Point(first.clientX, first.clientY), - offset = newPoint.subtract(this._startPoint); - - if (!offset.x && !offset.y) { return; } - if (L.Browser.touch && Math.abs(offset.x) + Math.abs(offset.y) < 3) { return; } - - L.DomEvent.preventDefault(e); - - if (!this._moved) { - this.fire('dragstart'); - - this._moved = true; - this._startPos = L.DomUtil.getPosition(this._element).subtract(offset); - - L.DomUtil.addClass(document.body, 'leaflet-dragging'); - this._lastTarget = e.target || e.srcElement; - L.DomUtil.addClass(this._lastTarget, 'leaflet-drag-target'); - } - - this._newPos = this._startPos.add(offset); - this._moving = true; - - L.Util.cancelAnimFrame(this._animRequest); - this._animRequest = L.Util.requestAnimFrame(this._updatePosition, this, true, this._dragStartTarget); - }, - - _updatePosition: function () { - this.fire('predrag'); - L.DomUtil.setPosition(this._element, this._newPos); - this.fire('drag'); - }, - - _onUp: function () { - L.DomUtil.removeClass(document.body, 'leaflet-dragging'); - - if (this._lastTarget) { - L.DomUtil.removeClass(this._lastTarget, 'leaflet-drag-target'); - this._lastTarget = null; - } - - for (var i in L.Draggable.MOVE) { - L.DomEvent - .off(document, L.Draggable.MOVE[i], this._onMove) - .off(document, L.Draggable.END[i], this._onUp); - } - - L.DomUtil.enableImageDrag(); - L.DomUtil.enableTextSelection(); - - if (this._moved && this._moving) { - // ensure drag is not fired after dragend - L.Util.cancelAnimFrame(this._animRequest); - - this.fire('dragend', { - distance: this._newPos.distanceTo(this._startPos) - }); - } - - this._moving = false; - } -}); - - -/* - L.Handler is a base class for handler classes that are used internally to inject - interaction features like dragging to classes like Map and Marker. -*/ - -L.Handler = L.Class.extend({ - initialize: function (map) { - this._map = map; - }, - - enable: function () { - if (this._enabled) { return; } - - this._enabled = true; - this.addHooks(); - }, - - disable: function () { - if (!this._enabled) { return; } - - this._enabled = false; - this.removeHooks(); - }, - - enabled: function () { - return !!this._enabled; - } -}); - - -/* - * L.Handler.MapDrag is used to make the map draggable (with panning inertia), enabled by default. - */ - -L.Map.mergeOptions({ - dragging: true, - - inertia: !L.Browser.android23, - inertiaDeceleration: 3400, // px/s^2 - inertiaMaxSpeed: Infinity, // px/s - inertiaThreshold: L.Browser.touch ? 32 : 18, // ms - easeLinearity: 0.25, - - // TODO refactor, move to CRS - worldCopyJump: false -}); - -L.Map.Drag = L.Handler.extend({ - addHooks: function () { - if (!this._draggable) { - var map = this._map; - - this._draggable = new L.Draggable(map._mapPane, map._container); - - this._draggable.on({ - 'dragstart': this._onDragStart, - 'drag': this._onDrag, - 'dragend': this._onDragEnd - }, this); - - if (map.options.worldCopyJump) { - this._draggable.on('predrag', this._onPreDrag, this); - map.on('viewreset', this._onViewReset, this); - - map.whenReady(this._onViewReset, this); - } - } - this._draggable.enable(); - }, - - removeHooks: function () { - this._draggable.disable(); - }, - - moved: function () { - return this._draggable && this._draggable._moved; - }, - - _onDragStart: function () { - var map = this._map; - - if (map._panAnim) { - map._panAnim.stop(); - } - - map - .fire('movestart') - .fire('dragstart'); - - if (map.options.inertia) { - this._positions = []; - this._times = []; - } - }, - - _onDrag: function () { - if (this._map.options.inertia) { - var time = this._lastTime = +new Date(), - pos = this._lastPos = this._draggable._newPos; - - this._positions.push(pos); - this._times.push(time); - - if (time - this._times[0] > 200) { - this._positions.shift(); - this._times.shift(); - } - } - - this._map - .fire('move') - .fire('drag'); - }, - - _onViewReset: function () { - // TODO fix hardcoded Earth values - var pxCenter = this._map.getSize()._divideBy(2), - pxWorldCenter = this._map.latLngToLayerPoint([0, 0]); - - this._initialWorldOffset = pxWorldCenter.subtract(pxCenter).x; - this._worldWidth = this._map.project([0, 180]).x; - }, - - _onPreDrag: function () { - // TODO refactor to be able to adjust map pane position after zoom - var worldWidth = this._worldWidth, - halfWidth = Math.round(worldWidth / 2), - dx = this._initialWorldOffset, - x = this._draggable._newPos.x, - newX1 = (x - halfWidth + dx) % worldWidth + halfWidth - dx, - newX2 = (x + halfWidth + dx) % worldWidth - halfWidth - dx, - newX = Math.abs(newX1 + dx) < Math.abs(newX2 + dx) ? newX1 : newX2; - - this._draggable._newPos.x = newX; - }, - - _onDragEnd: function (e) { - var map = this._map, - options = map.options, - delay = +new Date() - this._lastTime, - - noInertia = !options.inertia || delay > options.inertiaThreshold || !this._positions[0]; - - map.fire('dragend', e); - - if (noInertia) { - map.fire('moveend'); - - } else { - - var direction = this._lastPos.subtract(this._positions[0]), - duration = (this._lastTime + delay - this._times[0]) / 1000, - ease = options.easeLinearity, - - speedVector = direction.multiplyBy(ease / duration), - speed = speedVector.distanceTo([0, 0]), - - limitedSpeed = Math.min(options.inertiaMaxSpeed, speed), - limitedSpeedVector = speedVector.multiplyBy(limitedSpeed / speed), - - decelerationDuration = limitedSpeed / (options.inertiaDeceleration * ease), - offset = limitedSpeedVector.multiplyBy(-decelerationDuration / 2).round(); - - if (!offset.x || !offset.y) { - map.fire('moveend'); - - } else { - offset = map._limitOffset(offset, map.options.maxBounds); - - L.Util.requestAnimFrame(function () { - map.panBy(offset, { - duration: decelerationDuration, - easeLinearity: ease, - noMoveStart: true - }); - }); - } - } - } -}); - -L.Map.addInitHook('addHandler', 'dragging', L.Map.Drag); - - -/* - * L.Handler.DoubleClickZoom is used to handle double-click zoom on the map, enabled by default. - */ - -L.Map.mergeOptions({ - doubleClickZoom: true -}); - -L.Map.DoubleClickZoom = L.Handler.extend({ - addHooks: function () { - this._map.on('dblclick', this._onDoubleClick, this); - }, - - removeHooks: function () { - this._map.off('dblclick', this._onDoubleClick, this); - }, - - _onDoubleClick: function (e) { - var map = this._map, - zoom = map.getZoom() + (e.originalEvent.shiftKey ? -1 : 1); - - if (map.options.doubleClickZoom === 'center') { - map.setZoom(zoom); - } else { - map.setZoomAround(e.containerPoint, zoom); - } - } -}); - -L.Map.addInitHook('addHandler', 'doubleClickZoom', L.Map.DoubleClickZoom); - - -/* - * L.Handler.ScrollWheelZoom is used by L.Map to enable mouse scroll wheel zoom on the map. - */ - -L.Map.mergeOptions({ - scrollWheelZoom: true -}); - -L.Map.ScrollWheelZoom = L.Handler.extend({ - addHooks: function () { - L.DomEvent.on(this._map._container, 'mousewheel', this._onWheelScroll, this); - L.DomEvent.on(this._map._container, 'MozMousePixelScroll', L.DomEvent.preventDefault); - this._delta = 0; - }, - - removeHooks: function () { - L.DomEvent.off(this._map._container, 'mousewheel', this._onWheelScroll); - L.DomEvent.off(this._map._container, 'MozMousePixelScroll', L.DomEvent.preventDefault); - }, - - _onWheelScroll: function (e) { - var delta = L.DomEvent.getWheelDelta(e); - - this._delta += delta; - this._lastMousePos = this._map.mouseEventToContainerPoint(e); - - if (!this._startTime) { - this._startTime = +new Date(); - } - - var left = Math.max(40 - (+new Date() - this._startTime), 0); - - clearTimeout(this._timer); - this._timer = setTimeout(L.bind(this._performZoom, this), left); - - L.DomEvent.preventDefault(e); - L.DomEvent.stopPropagation(e); - }, - - _performZoom: function () { - var map = this._map, - delta = this._delta, - zoom = map.getZoom(); - - delta = delta > 0 ? Math.ceil(delta) : Math.floor(delta); - delta = Math.max(Math.min(delta, 4), -4); - delta = map._limitZoom(zoom + delta) - zoom; - - this._delta = 0; - this._startTime = null; - - if (!delta) { return; } - - if (map.options.scrollWheelZoom === 'center') { - map.setZoom(zoom + delta); - } else { - map.setZoomAround(this._lastMousePos, zoom + delta); - } - } -}); - -L.Map.addInitHook('addHandler', 'scrollWheelZoom', L.Map.ScrollWheelZoom); - - -/* - * Extends the event handling code with double tap support for mobile browsers. - */ - -L.extend(L.DomEvent, { - - _touchstart: L.Browser.msPointer ? 'MSPointerDown' : L.Browser.pointer ? 'pointerdown' : 'touchstart', - _touchend: L.Browser.msPointer ? 'MSPointerUp' : L.Browser.pointer ? 'pointerup' : 'touchend', - - // inspired by Zepto touch code by Thomas Fuchs - addDoubleTapListener: function (obj, handler, id) { - var last, - doubleTap = false, - delay = 250, - touch, - pre = '_leaflet_', - touchstart = this._touchstart, - touchend = this._touchend, - trackedTouches = []; - - function onTouchStart(e) { - var count; - - if (L.Browser.pointer) { - trackedTouches.push(e.pointerId); - count = trackedTouches.length; - } else { - count = e.touches.length; - } - if (count > 1) { - return; - } - - var now = Date.now(), - delta = now - (last || now); - - touch = e.touches ? e.touches[0] : e; - doubleTap = (delta > 0 && delta <= delay); - last = now; - } - - function onTouchEnd(e) { - if (L.Browser.pointer) { - var idx = trackedTouches.indexOf(e.pointerId); - if (idx === -1) { - return; - } - trackedTouches.splice(idx, 1); - } - - if (doubleTap) { - if (L.Browser.pointer) { - // work around .type being readonly with MSPointer* events - var newTouch = { }, - prop; - - // jshint forin:false - for (var i in touch) { - prop = touch[i]; - if (typeof prop === 'function') { - newTouch[i] = prop.bind(touch); - } else { - newTouch[i] = prop; - } - } - touch = newTouch; - } - touch.type = 'dblclick'; - handler(touch); - last = null; - } - } - obj[pre + touchstart + id] = onTouchStart; - obj[pre + touchend + id] = onTouchEnd; - - // on pointer we need to listen on the document, otherwise a drag starting on the map and moving off screen - // will not come through to us, so we will lose track of how many touches are ongoing - var endElement = L.Browser.pointer ? document.documentElement : obj; - - obj.addEventListener(touchstart, onTouchStart, false); - endElement.addEventListener(touchend, onTouchEnd, false); - - if (L.Browser.pointer) { - endElement.addEventListener(L.DomEvent.POINTER_CANCEL, onTouchEnd, false); - } - - return this; - }, - - removeDoubleTapListener: function (obj, id) { - var pre = '_leaflet_'; - - obj.removeEventListener(this._touchstart, obj[pre + this._touchstart + id], false); - (L.Browser.pointer ? document.documentElement : obj).removeEventListener( - this._touchend, obj[pre + this._touchend + id], false); - - if (L.Browser.pointer) { - document.documentElement.removeEventListener(L.DomEvent.POINTER_CANCEL, obj[pre + this._touchend + id], - false); - } - - return this; - } -}); - - -/* - * Extends L.DomEvent to provide touch support for Internet Explorer and Windows-based devices. - */ - -L.extend(L.DomEvent, { - - //static - POINTER_DOWN: L.Browser.msPointer ? 'MSPointerDown' : 'pointerdown', - POINTER_MOVE: L.Browser.msPointer ? 'MSPointerMove' : 'pointermove', - POINTER_UP: L.Browser.msPointer ? 'MSPointerUp' : 'pointerup', - POINTER_CANCEL: L.Browser.msPointer ? 'MSPointerCancel' : 'pointercancel', - - _pointers: [], - _pointerDocumentListener: false, - - // Provides a touch events wrapper for (ms)pointer events. - // Based on changes by veproza https://github.com/CloudMade/Leaflet/pull/1019 - //ref http://www.w3.org/TR/pointerevents/ https://www.w3.org/Bugs/Public/show_bug.cgi?id=22890 - - addPointerListener: function (obj, type, handler, id) { - - switch (type) { - case 'touchstart': - return this.addPointerListenerStart(obj, type, handler, id); - case 'touchend': - return this.addPointerListenerEnd(obj, type, handler, id); - case 'touchmove': - return this.addPointerListenerMove(obj, type, handler, id); - default: - throw 'Unknown touch event type'; - } - }, - - addPointerListenerStart: function (obj, type, handler, id) { - var pre = '_leaflet_', - pointers = this._pointers; - - var cb = function (e) { - if (e.pointerType !== 'mouse' && e.pointerType !== e.MSPOINTER_TYPE_MOUSE) { - L.DomEvent.preventDefault(e); - } - - var alreadyInArray = false; - for (var i = 0; i < pointers.length; i++) { - if (pointers[i].pointerId === e.pointerId) { - alreadyInArray = true; - break; - } - } - if (!alreadyInArray) { - pointers.push(e); - } - - e.touches = pointers.slice(); - e.changedTouches = [e]; - - handler(e); - }; - - obj[pre + 'touchstart' + id] = cb; - obj.addEventListener(this.POINTER_DOWN, cb, false); - - // need to also listen for end events to keep the _pointers list accurate - // this needs to be on the body and never go away - if (!this._pointerDocumentListener) { - var internalCb = function (e) { - for (var i = 0; i < pointers.length; i++) { - if (pointers[i].pointerId === e.pointerId) { - pointers.splice(i, 1); - break; - } - } - }; - //We listen on the documentElement as any drags that end by moving the touch off the screen get fired there - document.documentElement.addEventListener(this.POINTER_UP, internalCb, false); - document.documentElement.addEventListener(this.POINTER_CANCEL, internalCb, false); - - this._pointerDocumentListener = true; - } - - return this; - }, - - addPointerListenerMove: function (obj, type, handler, id) { - var pre = '_leaflet_', - touches = this._pointers; - - function cb(e) { - - // don't fire touch moves when mouse isn't down - if ((e.pointerType === e.MSPOINTER_TYPE_MOUSE || e.pointerType === 'mouse') && e.buttons === 0) { return; } - - for (var i = 0; i < touches.length; i++) { - if (touches[i].pointerId === e.pointerId) { - touches[i] = e; - break; - } - } - - e.touches = touches.slice(); - e.changedTouches = [e]; - - handler(e); - } - - obj[pre + 'touchmove' + id] = cb; - obj.addEventListener(this.POINTER_MOVE, cb, false); - - return this; - }, - - addPointerListenerEnd: function (obj, type, handler, id) { - var pre = '_leaflet_', - touches = this._pointers; - - var cb = function (e) { - for (var i = 0; i < touches.length; i++) { - if (touches[i].pointerId === e.pointerId) { - touches.splice(i, 1); - break; - } - } - - e.touches = touches.slice(); - e.changedTouches = [e]; - - handler(e); - }; - - obj[pre + 'touchend' + id] = cb; - obj.addEventListener(this.POINTER_UP, cb, false); - obj.addEventListener(this.POINTER_CANCEL, cb, false); - - return this; - }, - - removePointerListener: function (obj, type, id) { - var pre = '_leaflet_', - cb = obj[pre + type + id]; - - switch (type) { - case 'touchstart': - obj.removeEventListener(this.POINTER_DOWN, cb, false); - break; - case 'touchmove': - obj.removeEventListener(this.POINTER_MOVE, cb, false); - break; - case 'touchend': - obj.removeEventListener(this.POINTER_UP, cb, false); - obj.removeEventListener(this.POINTER_CANCEL, cb, false); - break; - } - - return this; - } -}); - - -/* - * L.Handler.TouchZoom is used by L.Map to add pinch zoom on supported mobile browsers. - */ - -L.Map.mergeOptions({ - touchZoom: L.Browser.touch && !L.Browser.android23, - bounceAtZoomLimits: true -}); - -L.Map.TouchZoom = L.Handler.extend({ - addHooks: function () { - L.DomEvent.on(this._map._container, 'touchstart', this._onTouchStart, this); - }, - - removeHooks: function () { - L.DomEvent.off(this._map._container, 'touchstart', this._onTouchStart, this); - }, - - _onTouchStart: function (e) { - var map = this._map; - - if (!e.touches || e.touches.length !== 2 || map._animatingZoom || this._zooming) { return; } - - var p1 = map.mouseEventToLayerPoint(e.touches[0]), - p2 = map.mouseEventToLayerPoint(e.touches[1]), - viewCenter = map._getCenterLayerPoint(); - - this._startCenter = p1.add(p2)._divideBy(2); - this._startDist = p1.distanceTo(p2); - - this._moved = false; - this._zooming = true; - - this._centerOffset = viewCenter.subtract(this._startCenter); - - if (map._panAnim) { - map._panAnim.stop(); - } - - L.DomEvent - .on(document, 'touchmove', this._onTouchMove, this) - .on(document, 'touchend', this._onTouchEnd, this); - - L.DomEvent.preventDefault(e); - }, - - _onTouchMove: function (e) { - var map = this._map; - - if (!e.touches || e.touches.length !== 2 || !this._zooming) { return; } - - var p1 = map.mouseEventToLayerPoint(e.touches[0]), - p2 = map.mouseEventToLayerPoint(e.touches[1]); - - this._scale = p1.distanceTo(p2) / this._startDist; - this._delta = p1._add(p2)._divideBy(2)._subtract(this._startCenter); - - if (this._scale === 1) { return; } - - if (!map.options.bounceAtZoomLimits) { - if ((map.getZoom() === map.getMinZoom() && this._scale < 1) || - (map.getZoom() === map.getMaxZoom() && this._scale > 1)) { return; } - } - - if (!this._moved) { - L.DomUtil.addClass(map._mapPane, 'leaflet-touching'); - - map - .fire('movestart') - .fire('zoomstart'); - - this._moved = true; - } - - L.Util.cancelAnimFrame(this._animRequest); - this._animRequest = L.Util.requestAnimFrame( - this._updateOnMove, this, true, this._map._container); - - L.DomEvent.preventDefault(e); - }, - - _updateOnMove: function () { - var map = this._map, - origin = this._getScaleOrigin(), - center = map.layerPointToLatLng(origin), - zoom = map.getScaleZoom(this._scale); - - map._animateZoom(center, zoom, this._startCenter, this._scale, this._delta, false, true); - }, - - _onTouchEnd: function () { - if (!this._moved || !this._zooming) { - this._zooming = false; - return; - } - - var map = this._map; - - this._zooming = false; - L.DomUtil.removeClass(map._mapPane, 'leaflet-touching'); - L.Util.cancelAnimFrame(this._animRequest); - - L.DomEvent - .off(document, 'touchmove', this._onTouchMove) - .off(document, 'touchend', this._onTouchEnd); - - var origin = this._getScaleOrigin(), - center = map.layerPointToLatLng(origin), - - oldZoom = map.getZoom(), - floatZoomDelta = map.getScaleZoom(this._scale) - oldZoom, - roundZoomDelta = (floatZoomDelta > 0 ? - Math.ceil(floatZoomDelta) : Math.floor(floatZoomDelta)), - - zoom = map._limitZoom(oldZoom + roundZoomDelta), - scale = map.getZoomScale(zoom) / this._scale; - - map._animateZoom(center, zoom, origin, scale); - }, - - _getScaleOrigin: function () { - var centerOffset = this._centerOffset.subtract(this._delta).divideBy(this._scale); - return this._startCenter.add(centerOffset); - } -}); - -L.Map.addInitHook('addHandler', 'touchZoom', L.Map.TouchZoom); - - -/* - * L.Map.Tap is used to enable mobile hacks like quick taps and long hold. - */ - -L.Map.mergeOptions({ - tap: true, - tapTolerance: 15 -}); - -L.Map.Tap = L.Handler.extend({ - addHooks: function () { - L.DomEvent.on(this._map._container, 'touchstart', this._onDown, this); - }, - - removeHooks: function () { - L.DomEvent.off(this._map._container, 'touchstart', this._onDown, this); - }, - - _onDown: function (e) { - if (!e.touches) { return; } - - /* - * If we have turned off dragging and zooming, then this is basically a - * set of static images. At that point, we expect to be able to treat it as an - * image - i.e. click on it and scroll the underlying window. - * So we preventDefault only when dragging and zooming are enabled - * - * We want to do the checks for dragging, etc only on a map because - * they won't be defined on the oher layers. So if this has a _map - * defined on it, we want to preventDefault, and otherwise, it is a - * map and we want to check for the other configurations. - */ - var mapOptions = this._map.options; - if (mapOptions.dragging || mapOptions.doubleClickZoom || - mapOptions.scrollWheelZoom || mapOptions.touchZoom) { - L.DomEvent.preventDefault(e); - } - - this._fireClick = true; - - // don't simulate click or track longpress if more than 1 touch - if (e.touches.length > 1) { - this._fireClick = false; - clearTimeout(this._holdTimeout); - return; - } - - var first = e.touches[0], - el = first.target; - - this._startPos = this._newPos = new L.Point(first.clientX, first.clientY); - - // if touching a link, highlight it - if (el.tagName && el.tagName.toLowerCase() === 'a') { - L.DomUtil.addClass(el, 'leaflet-active'); - } - - // simulate long hold but setting a timeout - this._holdTimeout = setTimeout(L.bind(function () { - if (this._isTapValid()) { - this._fireClick = false; - this._onUp(); - this._simulateEvent('contextmenu', first); - } - }, this), 1000); - - L.DomEvent - .on(document, 'touchmove', this._onMove, this) - .on(document, 'touchend', this._onUp, this); - }, - - _onUp: function (e) { - clearTimeout(this._holdTimeout); - - L.DomEvent - .off(document, 'touchmove', this._onMove, this) - .off(document, 'touchend', this._onUp, this); - - if (this._fireClick && e && e.changedTouches) { - - var first = e.changedTouches[0], - el = first.target; - - if (el && el.tagName && el.tagName.toLowerCase() === 'a') { - L.DomUtil.removeClass(el, 'leaflet-active'); - } - - // simulate click if the touch didn't move too much - if (this._isTapValid()) { - this._simulateEvent('click', first); - } - } - }, - - _isTapValid: function () { - return this._newPos.distanceTo(this._startPos) <= this._map.options.tapTolerance; - }, - - _onMove: function (e) { - var first = e.touches[0]; - this._newPos = new L.Point(first.clientX, first.clientY); - }, - - _simulateEvent: function (type, e) { - var simulatedEvent = document.createEvent('MouseEvents'); - - simulatedEvent._simulated = true; - e.target._simulatedClick = true; - - simulatedEvent.initMouseEvent( - type, true, true, window, 1, - e.screenX, e.screenY, - e.clientX, e.clientY, - false, false, false, false, 0, null); - - e.target.dispatchEvent(simulatedEvent); - } -}); - -if (L.Browser.touch && !L.Browser.pointer) { - L.Map.addInitHook('addHandler', 'tap', L.Map.Tap); -} - - -/* - * L.Handler.ShiftDragZoom is used to add shift-drag zoom interaction to the map - * (zoom to a selected bounding box), enabled by default. - */ - -L.Map.mergeOptions({ - boxZoom: true -}); - -L.Map.BoxZoom = L.Handler.extend({ - initialize: function (map) { - this._map = map; - this._container = map._container; - this._pane = map._panes.overlayPane; - this._moved = false; - }, - - addHooks: function () { - L.DomEvent.on(this._container, 'mousedown', this._onMouseDown, this); - }, - - removeHooks: function () { - L.DomEvent.off(this._container, 'mousedown', this._onMouseDown); - this._moved = false; - }, - - moved: function () { - return this._moved; - }, - - _onMouseDown: function (e) { - this._moved = false; - - if (!e.shiftKey || ((e.which !== 1) && (e.button !== 1))) { return false; } - - L.DomUtil.disableTextSelection(); - L.DomUtil.disableImageDrag(); - - this._startLayerPoint = this._map.mouseEventToLayerPoint(e); - - L.DomEvent - .on(document, 'mousemove', this._onMouseMove, this) - .on(document, 'mouseup', this._onMouseUp, this) - .on(document, 'keydown', this._onKeyDown, this); - }, - - _onMouseMove: function (e) { - if (!this._moved) { - this._box = L.DomUtil.create('div', 'leaflet-zoom-box', this._pane); - L.DomUtil.setPosition(this._box, this._startLayerPoint); - - //TODO refactor: move cursor to styles - this._container.style.cursor = 'crosshair'; - this._map.fire('boxzoomstart'); - } - - var startPoint = this._startLayerPoint, - box = this._box, - - layerPoint = this._map.mouseEventToLayerPoint(e), - offset = layerPoint.subtract(startPoint), - - newPos = new L.Point( - Math.min(layerPoint.x, startPoint.x), - Math.min(layerPoint.y, startPoint.y)); - - L.DomUtil.setPosition(box, newPos); - - this._moved = true; - - // TODO refactor: remove hardcoded 4 pixels - box.style.width = (Math.max(0, Math.abs(offset.x) - 4)) + 'px'; - box.style.height = (Math.max(0, Math.abs(offset.y) - 4)) + 'px'; - }, - - _finish: function () { - if (this._moved) { - this._pane.removeChild(this._box); - this._container.style.cursor = ''; - } - - L.DomUtil.enableTextSelection(); - L.DomUtil.enableImageDrag(); - - L.DomEvent - .off(document, 'mousemove', this._onMouseMove) - .off(document, 'mouseup', this._onMouseUp) - .off(document, 'keydown', this._onKeyDown); - }, - - _onMouseUp: function (e) { - - this._finish(); - - var map = this._map, - layerPoint = map.mouseEventToLayerPoint(e); - - if (this._startLayerPoint.equals(layerPoint)) { return; } - - var bounds = new L.LatLngBounds( - map.layerPointToLatLng(this._startLayerPoint), - map.layerPointToLatLng(layerPoint)); - - map.fitBounds(bounds); - - map.fire('boxzoomend', { - boxZoomBounds: bounds - }); - }, - - _onKeyDown: function (e) { - if (e.keyCode === 27) { - this._finish(); - } - } -}); - -L.Map.addInitHook('addHandler', 'boxZoom', L.Map.BoxZoom); - - -/* - * L.Map.Keyboard is handling keyboard interaction with the map, enabled by default. - */ - -L.Map.mergeOptions({ - keyboard: true, - keyboardPanOffset: 80, - keyboardZoomOffset: 1 -}); - -L.Map.Keyboard = L.Handler.extend({ - - keyCodes: { - left: [37], - right: [39], - down: [40], - up: [38], - zoomIn: [187, 107, 61, 171], - zoomOut: [189, 109, 173] - }, - - initialize: function (map) { - this._map = map; - - this._setPanOffset(map.options.keyboardPanOffset); - this._setZoomOffset(map.options.keyboardZoomOffset); - }, - - addHooks: function () { - var container = this._map._container; - - // make the container focusable by tabbing - if (container.tabIndex === -1) { - container.tabIndex = '0'; - } - - L.DomEvent - .on(container, 'focus', this._onFocus, this) - .on(container, 'blur', this._onBlur, this) - .on(container, 'mousedown', this._onMouseDown, this); - - this._map - .on('focus', this._addHooks, this) - .on('blur', this._removeHooks, this); - }, - - removeHooks: function () { - this._removeHooks(); - - var container = this._map._container; - - L.DomEvent - .off(container, 'focus', this._onFocus, this) - .off(container, 'blur', this._onBlur, this) - .off(container, 'mousedown', this._onMouseDown, this); - - this._map - .off('focus', this._addHooks, this) - .off('blur', this._removeHooks, this); - }, - - _onMouseDown: function () { - if (this._focused) { return; } - - var body = document.body, - docEl = document.documentElement, - top = body.scrollTop || docEl.scrollTop, - left = body.scrollLeft || docEl.scrollLeft; - - this._map._container.focus(); - - window.scrollTo(left, top); - }, - - _onFocus: function () { - this._focused = true; - this._map.fire('focus'); - }, - - _onBlur: function () { - this._focused = false; - this._map.fire('blur'); - }, - - _setPanOffset: function (pan) { - var keys = this._panKeys = {}, - codes = this.keyCodes, - i, len; - - for (i = 0, len = codes.left.length; i < len; i++) { - keys[codes.left[i]] = [-1 * pan, 0]; - } - for (i = 0, len = codes.right.length; i < len; i++) { - keys[codes.right[i]] = [pan, 0]; - } - for (i = 0, len = codes.down.length; i < len; i++) { - keys[codes.down[i]] = [0, pan]; - } - for (i = 0, len = codes.up.length; i < len; i++) { - keys[codes.up[i]] = [0, -1 * pan]; - } - }, - - _setZoomOffset: function (zoom) { - var keys = this._zoomKeys = {}, - codes = this.keyCodes, - i, len; - - for (i = 0, len = codes.zoomIn.length; i < len; i++) { - keys[codes.zoomIn[i]] = zoom; - } - for (i = 0, len = codes.zoomOut.length; i < len; i++) { - keys[codes.zoomOut[i]] = -zoom; - } - }, - - _addHooks: function () { - L.DomEvent.on(document, 'keydown', this._onKeyDown, this); - }, - - _removeHooks: function () { - L.DomEvent.off(document, 'keydown', this._onKeyDown, this); - }, - - _onKeyDown: function (e) { - var key = e.keyCode, - map = this._map; - - if (key in this._panKeys) { - - if (map._panAnim && map._panAnim._inProgress) { return; } - - map.panBy(this._panKeys[key]); - - if (map.options.maxBounds) { - map.panInsideBounds(map.options.maxBounds); - } - - } else if (key in this._zoomKeys) { - map.setZoom(map.getZoom() + this._zoomKeys[key]); - - } else { - return; - } - - L.DomEvent.stop(e); - } -}); - -L.Map.addInitHook('addHandler', 'keyboard', L.Map.Keyboard); - - -/* - * L.Handler.MarkerDrag is used internally by L.Marker to make the markers draggable. - */ - -L.Handler.MarkerDrag = L.Handler.extend({ - initialize: function (marker) { - this._marker = marker; - }, - - addHooks: function () { - var icon = this._marker._icon; - if (!this._draggable) { - this._draggable = new L.Draggable(icon, icon); - } - - this._draggable - .on('dragstart', this._onDragStart, this) - .on('drag', this._onDrag, this) - .on('dragend', this._onDragEnd, this); - this._draggable.enable(); - L.DomUtil.addClass(this._marker._icon, 'leaflet-marker-draggable'); - }, - - removeHooks: function () { - this._draggable - .off('dragstart', this._onDragStart, this) - .off('drag', this._onDrag, this) - .off('dragend', this._onDragEnd, this); - - this._draggable.disable(); - L.DomUtil.removeClass(this._marker._icon, 'leaflet-marker-draggable'); - }, - - moved: function () { - return this._draggable && this._draggable._moved; - }, - - _onDragStart: function () { - this._marker - .closePopup() - .fire('movestart') - .fire('dragstart'); - }, - - _onDrag: function () { - var marker = this._marker, - shadow = marker._shadow, - iconPos = L.DomUtil.getPosition(marker._icon), - latlng = marker._map.layerPointToLatLng(iconPos); - - // update shadow position - if (shadow) { - L.DomUtil.setPosition(shadow, iconPos); - } - - marker._latlng = latlng; - - marker - .fire('move', {latlng: latlng}) - .fire('drag'); - }, - - _onDragEnd: function (e) { - this._marker - .fire('moveend') - .fire('dragend', e); - } -}); - - -/* - * L.Control is a base class for implementing map controls. Handles positioning. - * All other controls extend from this class. - */ - -L.Control = L.Class.extend({ - options: { - position: 'topright' - }, - - initialize: function (options) { - L.setOptions(this, options); - }, - - getPosition: function () { - return this.options.position; - }, - - setPosition: function (position) { - var map = this._map; - - if (map) { - map.removeControl(this); - } - - this.options.position = position; - - if (map) { - map.addControl(this); - } - - return this; - }, - - getContainer: function () { - return this._container; - }, - - addTo: function (map) { - this._map = map; - - var container = this._container = this.onAdd(map), - pos = this.getPosition(), - corner = map._controlCorners[pos]; - - L.DomUtil.addClass(container, 'leaflet-control'); - - if (pos.indexOf('bottom') !== -1) { - corner.insertBefore(container, corner.firstChild); - } else { - corner.appendChild(container); - } - - return this; - }, - - removeFrom: function (map) { - var pos = this.getPosition(), - corner = map._controlCorners[pos]; - - corner.removeChild(this._container); - this._map = null; - - if (this.onRemove) { - this.onRemove(map); - } - - return this; - }, - - _refocusOnMap: function () { - if (this._map) { - this._map.getContainer().focus(); - } - } -}); - -L.control = function (options) { - return new L.Control(options); -}; - - -// adds control-related methods to L.Map - -L.Map.include({ - addControl: function (control) { - control.addTo(this); - return this; - }, - - removeControl: function (control) { - control.removeFrom(this); - return this; - }, - - _initControlPos: function () { - var corners = this._controlCorners = {}, - l = 'leaflet-', - container = this._controlContainer = - L.DomUtil.create('div', l + 'control-container', this._container); - - function createCorner(vSide, hSide) { - var className = l + vSide + ' ' + l + hSide; - - corners[vSide + hSide] = L.DomUtil.create('div', className, container); - } - - createCorner('top', 'left'); - createCorner('top', 'right'); - createCorner('bottom', 'left'); - createCorner('bottom', 'right'); - }, - - _clearControlPos: function () { - this._container.removeChild(this._controlContainer); - } -}); - - -/* - * L.Control.Zoom is used for the default zoom buttons on the map. - */ - -L.Control.Zoom = L.Control.extend({ - options: { - position: 'topleft', - zoomInText: '+', - zoomInTitle: 'Zoom in', - zoomOutText: '-', - zoomOutTitle: 'Zoom out' - }, - - onAdd: function (map) { - var zoomName = 'leaflet-control-zoom', - container = L.DomUtil.create('div', zoomName + ' leaflet-bar'); - - this._map = map; - - this._zoomInButton = this._createButton( - this.options.zoomInText, this.options.zoomInTitle, - zoomName + '-in', container, this._zoomIn, this); - this._zoomOutButton = this._createButton( - this.options.zoomOutText, this.options.zoomOutTitle, - zoomName + '-out', container, this._zoomOut, this); - - this._updateDisabled(); - map.on('zoomend zoomlevelschange', this._updateDisabled, this); - - return container; - }, - - onRemove: function (map) { - map.off('zoomend zoomlevelschange', this._updateDisabled, this); - }, - - _zoomIn: function (e) { - this._map.zoomIn(e.shiftKey ? 3 : 1); - }, - - _zoomOut: function (e) { - this._map.zoomOut(e.shiftKey ? 3 : 1); - }, - - _createButton: function (html, title, className, container, fn, context) { - var link = L.DomUtil.create('a', className, container); - link.innerHTML = html; - link.href = '#'; - link.title = title; - - var stop = L.DomEvent.stopPropagation; - - L.DomEvent - .on(link, 'click', stop) - .on(link, 'mousedown', stop) - .on(link, 'dblclick', stop) - .on(link, 'click', L.DomEvent.preventDefault) - .on(link, 'click', fn, context) - .on(link, 'click', this._refocusOnMap, context); - - return link; - }, - - _updateDisabled: function () { - var map = this._map, - className = 'leaflet-disabled'; - - L.DomUtil.removeClass(this._zoomInButton, className); - L.DomUtil.removeClass(this._zoomOutButton, className); - - if (map._zoom === map.getMinZoom()) { - L.DomUtil.addClass(this._zoomOutButton, className); - } - if (map._zoom === map.getMaxZoom()) { - L.DomUtil.addClass(this._zoomInButton, className); - } - } -}); - -L.Map.mergeOptions({ - zoomControl: true -}); - -L.Map.addInitHook(function () { - if (this.options.zoomControl) { - this.zoomControl = new L.Control.Zoom(); - this.addControl(this.zoomControl); - } -}); - -L.control.zoom = function (options) { - return new L.Control.Zoom(options); -}; - - - -/* - * L.Control.Attribution is used for displaying attribution on the map (added by default). - */ - -L.Control.Attribution = L.Control.extend({ - options: { - position: 'bottomright', - prefix: 'Leaflet' - }, - - initialize: function (options) { - L.setOptions(this, options); - - this._attributions = {}; - }, - - onAdd: function (map) { - this._container = L.DomUtil.create('div', 'leaflet-control-attribution'); - L.DomEvent.disableClickPropagation(this._container); - - for (var i in map._layers) { - if (map._layers[i].getAttribution) { - this.addAttribution(map._layers[i].getAttribution()); - } - } - - map - .on('layeradd', this._onLayerAdd, this) - .on('layerremove', this._onLayerRemove, this); - - this._update(); - - return this._container; - }, - - onRemove: function (map) { - map - .off('layeradd', this._onLayerAdd) - .off('layerremove', this._onLayerRemove); - - }, - - setPrefix: function (prefix) { - this.options.prefix = prefix; - this._update(); - return this; - }, - - addAttribution: function (text) { - if (!text) { return; } - - if (!this._attributions[text]) { - this._attributions[text] = 0; - } - this._attributions[text]++; - - this._update(); - - return this; - }, - - removeAttribution: function (text) { - if (!text) { return; } - - if (this._attributions[text]) { - this._attributions[text]--; - this._update(); - } - - return this; - }, - - _update: function () { - if (!this._map) { return; } - - var attribs = []; - - for (var i in this._attributions) { - if (this._attributions[i]) { - attribs.push(i); - } - } - - var prefixAndAttribs = []; - - if (this.options.prefix) { - prefixAndAttribs.push(this.options.prefix); - } - if (attribs.length) { - prefixAndAttribs.push(attribs.join(', ')); - } - - this._container.innerHTML = prefixAndAttribs.join(' | '); - }, - - _onLayerAdd: function (e) { - if (e.layer.getAttribution) { - this.addAttribution(e.layer.getAttribution()); - } - }, - - _onLayerRemove: function (e) { - if (e.layer.getAttribution) { - this.removeAttribution(e.layer.getAttribution()); - } - } -}); - -L.Map.mergeOptions({ - attributionControl: true -}); - -L.Map.addInitHook(function () { - if (this.options.attributionControl) { - this.attributionControl = (new L.Control.Attribution()).addTo(this); - } -}); - -L.control.attribution = function (options) { - return new L.Control.Attribution(options); -}; - - -/* - * L.Control.Scale is used for displaying metric/imperial scale on the map. - */ - -L.Control.Scale = L.Control.extend({ - options: { - position: 'bottomleft', - maxWidth: 100, - metric: true, - imperial: true, - updateWhenIdle: false - }, - - onAdd: function (map) { - this._map = map; - - var className = 'leaflet-control-scale', - container = L.DomUtil.create('div', className), - options = this.options; - - this._addScales(options, className, container); - - map.on(options.updateWhenIdle ? 'moveend' : 'move', this._update, this); - map.whenReady(this._update, this); - - return container; - }, - - onRemove: function (map) { - map.off(this.options.updateWhenIdle ? 'moveend' : 'move', this._update, this); - }, - - _addScales: function (options, className, container) { - if (options.metric) { - this._mScale = L.DomUtil.create('div', className + '-line', container); - } - if (options.imperial) { - this._iScale = L.DomUtil.create('div', className + '-line', container); - } - }, - - _update: function () { - var bounds = this._map.getBounds(), - centerLat = bounds.getCenter().lat, - halfWorldMeters = 6378137 * Math.PI * Math.cos(centerLat * Math.PI / 180), - dist = halfWorldMeters * (bounds.getNorthEast().lng - bounds.getSouthWest().lng) / 180, - - size = this._map.getSize(), - options = this.options, - maxMeters = 0; - - if (size.x > 0) { - maxMeters = dist * (options.maxWidth / size.x); - } - - this._updateScales(options, maxMeters); - }, - - _updateScales: function (options, maxMeters) { - if (options.metric && maxMeters) { - this._updateMetric(maxMeters); - } - - if (options.imperial && maxMeters) { - this._updateImperial(maxMeters); - } - }, - - _updateMetric: function (maxMeters) { - var meters = this._getRoundNum(maxMeters); - - this._mScale.style.width = this._getScaleWidth(meters / maxMeters) + 'px'; - this._mScale.innerHTML = meters < 1000 ? meters + ' m' : (meters / 1000) + ' km'; - }, - - _updateImperial: function (maxMeters) { - var maxFeet = maxMeters * 3.2808399, - scale = this._iScale, - maxMiles, miles, feet; - - if (maxFeet > 5280) { - maxMiles = maxFeet / 5280; - miles = this._getRoundNum(maxMiles); - - scale.style.width = this._getScaleWidth(miles / maxMiles) + 'px'; - scale.innerHTML = miles + ' mi'; - - } else { - feet = this._getRoundNum(maxFeet); - - scale.style.width = this._getScaleWidth(feet / maxFeet) + 'px'; - scale.innerHTML = feet + ' ft'; - } - }, - - _getScaleWidth: function (ratio) { - return Math.round(this.options.maxWidth * ratio) - 10; - }, - - _getRoundNum: function (num) { - var pow10 = Math.pow(10, (Math.floor(num) + '').length - 1), - d = num / pow10; - - d = d >= 10 ? 10 : d >= 5 ? 5 : d >= 3 ? 3 : d >= 2 ? 2 : 1; - - return pow10 * d; - } -}); - -L.control.scale = function (options) { - return new L.Control.Scale(options); -}; - - -/* - * L.Control.Layers is a control to allow users to switch between different layers on the map. - */ - -L.Control.Layers = L.Control.extend({ - options: { - collapsed: true, - position: 'topright', - autoZIndex: true - }, - - initialize: function (baseLayers, overlays, options) { - L.setOptions(this, options); - - this._layers = {}; - this._lastZIndex = 0; - this._handlingClick = false; - - for (var i in baseLayers) { - this._addLayer(baseLayers[i], i); - } - - for (i in overlays) { - this._addLayer(overlays[i], i, true); - } - }, - - onAdd: function (map) { - this._initLayout(); - this._update(); - - map - .on('layeradd', this._onLayerChange, this) - .on('layerremove', this._onLayerChange, this); - - return this._container; - }, - - onRemove: function (map) { - map - .off('layeradd', this._onLayerChange, this) - .off('layerremove', this._onLayerChange, this); - }, - - addBaseLayer: function (layer, name) { - this._addLayer(layer, name); - this._update(); - return this; - }, - - addOverlay: function (layer, name) { - this._addLayer(layer, name, true); - this._update(); - return this; - }, - - removeLayer: function (layer) { - var id = L.stamp(layer); - delete this._layers[id]; - this._update(); - return this; - }, - - _initLayout: function () { - var className = 'leaflet-control-layers', - container = this._container = L.DomUtil.create('div', className); - - //Makes this work on IE10 Touch devices by stopping it from firing a mouseout event when the touch is released - container.setAttribute('aria-haspopup', true); - - if (!L.Browser.touch) { - L.DomEvent - .disableClickPropagation(container) - .disableScrollPropagation(container); - } else { - L.DomEvent.on(container, 'click', L.DomEvent.stopPropagation); - } - - var form = this._form = L.DomUtil.create('form', className + '-list'); - - if (this.options.collapsed) { - if (!L.Browser.android) { - L.DomEvent - .on(container, 'mouseover', this._expand, this) - .on(container, 'mouseout', this._collapse, this); - } - var link = this._layersLink = L.DomUtil.create('a', className + '-toggle', container); - link.href = '#'; - link.title = 'Layers'; - - if (L.Browser.touch) { - L.DomEvent - .on(link, 'click', L.DomEvent.stop) - .on(link, 'click', this._expand, this); - } - else { - L.DomEvent.on(link, 'focus', this._expand, this); - } - //Work around for Firefox android issue https://github.com/Leaflet/Leaflet/issues/2033 - L.DomEvent.on(form, 'click', function () { - setTimeout(L.bind(this._onInputClick, this), 0); - }, this); - - this._map.on('click', this._collapse, this); - // TODO keyboard accessibility - } else { - this._expand(); - } - - this._baseLayersList = L.DomUtil.create('div', className + '-base', form); - this._separator = L.DomUtil.create('div', className + '-separator', form); - this._overlaysList = L.DomUtil.create('div', className + '-overlays', form); - - container.appendChild(form); - }, - - _addLayer: function (layer, name, overlay) { - var id = L.stamp(layer); - - this._layers[id] = { - layer: layer, - name: name, - overlay: overlay - }; - - if (this.options.autoZIndex && layer.setZIndex) { - this._lastZIndex++; - layer.setZIndex(this._lastZIndex); - } - }, - - _update: function () { - if (!this._container) { - return; - } - - this._baseLayersList.innerHTML = ''; - this._overlaysList.innerHTML = ''; - - var baseLayersPresent = false, - overlaysPresent = false, - i, obj; - - for (i in this._layers) { - obj = this._layers[i]; - this._addItem(obj); - overlaysPresent = overlaysPresent || obj.overlay; - baseLayersPresent = baseLayersPresent || !obj.overlay; - } - - this._separator.style.display = overlaysPresent && baseLayersPresent ? '' : 'none'; - }, - - _onLayerChange: function (e) { - var obj = this._layers[L.stamp(e.layer)]; - - if (!obj) { return; } - - if (!this._handlingClick) { - this._update(); - } - - var type = obj.overlay ? - (e.type === 'layeradd' ? 'overlayadd' : 'overlayremove') : - (e.type === 'layeradd' ? 'baselayerchange' : null); - - if (type) { - this._map.fire(type, obj); - } - }, - - // IE7 bugs out if you create a radio dynamically, so you have to do it this hacky way (see http://bit.ly/PqYLBe) - _createRadioElement: function (name, checked) { - - var radioHtml = '= 0) { - this._onZoomTransitionEnd(); - } - }, - - _nothingToAnimate: function () { - return !this._container.getElementsByClassName('leaflet-zoom-animated').length; - }, - - _tryAnimatedZoom: function (center, zoom, options) { - - if (this._animatingZoom) { return true; } - - options = options || {}; - - // don't animate if disabled, not supported or zoom difference is too large - if (!this._zoomAnimated || options.animate === false || this._nothingToAnimate() || - Math.abs(zoom - this._zoom) > this.options.zoomAnimationThreshold) { return false; } - - // offset is the pixel coords of the zoom origin relative to the current center - var scale = this.getZoomScale(zoom), - offset = this._getCenterOffset(center)._divideBy(1 - 1 / scale), - origin = this._getCenterLayerPoint()._add(offset); - - // don't animate if the zoom origin isn't within one screen from the current center, unless forced - if (options.animate !== true && !this.getSize().contains(offset)) { return false; } - - this - .fire('movestart') - .fire('zoomstart'); - - this._animateZoom(center, zoom, origin, scale, null, true); - - return true; - }, - - _animateZoom: function (center, zoom, origin, scale, delta, backwards, forTouchZoom) { - - if (!forTouchZoom) { - this._animatingZoom = true; - } - - // put transform transition on all layers with leaflet-zoom-animated class - L.DomUtil.addClass(this._mapPane, 'leaflet-zoom-anim'); - - // remember what center/zoom to set after animation - this._animateToCenter = center; - this._animateToZoom = zoom; - - // disable any dragging during animation - if (L.Draggable) { - L.Draggable._disabled = true; - } - - L.Util.requestAnimFrame(function () { - this.fire('zoomanim', { - center: center, - zoom: zoom, - origin: origin, - scale: scale, - delta: delta, - backwards: backwards - }); - // horrible hack to work around a Chrome bug https://github.com/Leaflet/Leaflet/issues/3689 - setTimeout(L.bind(this._onZoomTransitionEnd, this), 250); - }, this); - }, - - _onZoomTransitionEnd: function () { - if (!this._animatingZoom) { return; } - - this._animatingZoom = false; - - L.DomUtil.removeClass(this._mapPane, 'leaflet-zoom-anim'); - - L.Util.requestAnimFrame(function () { - this._resetView(this._animateToCenter, this._animateToZoom, true, true); - - if (L.Draggable) { - L.Draggable._disabled = false; - } - }, this); - } -}); - - -/* - Zoom animation logic for L.TileLayer. -*/ - -L.TileLayer.include({ - _animateZoom: function (e) { - if (!this._animating) { - this._animating = true; - this._prepareBgBuffer(); - } - - var bg = this._bgBuffer, - transform = L.DomUtil.TRANSFORM, - initialTransform = e.delta ? L.DomUtil.getTranslateString(e.delta) : bg.style[transform], - scaleStr = L.DomUtil.getScaleString(e.scale, e.origin); - - bg.style[transform] = e.backwards ? - scaleStr + ' ' + initialTransform : - initialTransform + ' ' + scaleStr; - }, - - _endZoomAnim: function () { - var front = this._tileContainer, - bg = this._bgBuffer; - - front.style.visibility = ''; - front.parentNode.appendChild(front); // Bring to fore - - // force reflow - L.Util.falseFn(bg.offsetWidth); - - var zoom = this._map.getZoom(); - if (zoom > this.options.maxZoom || zoom < this.options.minZoom) { - this._clearBgBuffer(); - } - - this._animating = false; - }, - - _clearBgBuffer: function () { - var map = this._map; - - if (map && !map._animatingZoom && !map.touchZoom._zooming) { - this._bgBuffer.innerHTML = ''; - this._bgBuffer.style[L.DomUtil.TRANSFORM] = ''; - } - }, - - _prepareBgBuffer: function () { - - var front = this._tileContainer, - bg = this._bgBuffer; - - // if foreground layer doesn't have many tiles but bg layer does, - // keep the existing bg layer and just zoom it some more - - var bgLoaded = this._getLoadedTilesPercentage(bg), - frontLoaded = this._getLoadedTilesPercentage(front); - - if (bg && bgLoaded > 0.5 && frontLoaded < 0.5) { - - front.style.visibility = 'hidden'; - this._stopLoadingImages(front); - return; - } - - // prepare the buffer to become the front tile pane - bg.style.visibility = 'hidden'; - bg.style[L.DomUtil.TRANSFORM] = ''; - - // switch out the current layer to be the new bg layer (and vice-versa) - this._tileContainer = bg; - bg = this._bgBuffer = front; - - this._stopLoadingImages(bg); - - //prevent bg buffer from clearing right after zoom - clearTimeout(this._clearBgBufferTimer); - }, - - _getLoadedTilesPercentage: function (container) { - var tiles = container.getElementsByTagName('img'), - i, len, count = 0; - - for (i = 0, len = tiles.length; i < len; i++) { - if (tiles[i].complete) { - count++; - } - } - return count / len; - }, - - // stops loading all tiles in the background layer - _stopLoadingImages: function (container) { - var tiles = Array.prototype.slice.call(container.getElementsByTagName('img')), - i, len, tile; - - for (i = 0, len = tiles.length; i < len; i++) { - tile = tiles[i]; - - if (!tile.complete) { - tile.onload = L.Util.falseFn; - tile.onerror = L.Util.falseFn; - tile.src = L.Util.emptyImageUrl; - - tile.parentNode.removeChild(tile); - } - } - } -}); - - -/* - * Provides L.Map with convenient shortcuts for using browser geolocation features. - */ - -L.Map.include({ - _defaultLocateOptions: { - watch: false, - setView: false, - maxZoom: Infinity, - timeout: 10000, - maximumAge: 0, - enableHighAccuracy: false - }, - - locate: function (/*Object*/ options) { - - options = this._locateOptions = L.extend(this._defaultLocateOptions, options); - - if (!navigator.geolocation) { - this._handleGeolocationError({ - code: 0, - message: 'Geolocation not supported.' - }); - return this; - } - - var onResponse = L.bind(this._handleGeolocationResponse, this), - onError = L.bind(this._handleGeolocationError, this); - - if (options.watch) { - this._locationWatchId = - navigator.geolocation.watchPosition(onResponse, onError, options); - } else { - navigator.geolocation.getCurrentPosition(onResponse, onError, options); - } - return this; - }, - - stopLocate: function () { - if (navigator.geolocation) { - navigator.geolocation.clearWatch(this._locationWatchId); - } - if (this._locateOptions) { - this._locateOptions.setView = false; - } - return this; - }, - - _handleGeolocationError: function (error) { - var c = error.code, - message = error.message || - (c === 1 ? 'permission denied' : - (c === 2 ? 'position unavailable' : 'timeout')); - - if (this._locateOptions.setView && !this._loaded) { - this.fitWorld(); - } - - this.fire('locationerror', { - code: c, - message: 'Geolocation error: ' + message + '.' - }); - }, - - _handleGeolocationResponse: function (pos) { - var lat = pos.coords.latitude, - lng = pos.coords.longitude, - latlng = new L.LatLng(lat, lng), - - latAccuracy = 180 * pos.coords.accuracy / 40075017, - lngAccuracy = latAccuracy / Math.cos(L.LatLng.DEG_TO_RAD * lat), - - bounds = L.latLngBounds( - [lat - latAccuracy, lng - lngAccuracy], - [lat + latAccuracy, lng + lngAccuracy]), - - options = this._locateOptions; - - if (options.setView) { - var zoom = Math.min(this.getBoundsZoom(bounds), options.maxZoom); - this.setView(latlng, zoom); - } - - var data = { - latlng: latlng, - bounds: bounds, - timestamp: pos.timestamp - }; - - for (var i in pos.coords) { - if (typeof pos.coords[i] === 'number') { - data[i] = pos.coords[i]; - } - } - - this.fire('locationfound', data); - } -}); - - -}(window, document)); diff --git a/www/manual_lib/leaflet/dist/leaflet.js b/www/manual_lib/leaflet/dist/leaflet.js deleted file mode 100644 index ee5ff5a1d..000000000 --- a/www/manual_lib/leaflet/dist/leaflet.js +++ /dev/null @@ -1,9 +0,0 @@ -/* - Leaflet, a JavaScript library for mobile-friendly interactive maps. http://leafletjs.com - (c) 2010-2013, Vladimir Agafonkin - (c) 2010-2011, CloudMade -*/ -!function(t,e,i){var n=t.L,o={};o.version="0.7.7","object"==typeof module&&"object"==typeof module.exports?module.exports=o:"function"==typeof define&&define.amd&&define(o),o.noConflict=function(){return t.L=n,this},t.L=o,o.Util={extend:function(t){var e,i,n,o,s=Array.prototype.slice.call(arguments,1);for(i=0,n=s.length;n>i;i++){o=s[i]||{};for(e in o)o.hasOwnProperty(e)&&(t[e]=o[e])}return t},bind:function(t,e){var i=arguments.length>2?Array.prototype.slice.call(arguments,2):null;return function(){return t.apply(e,i||arguments)}},stamp:function(){var t=0,e="_leaflet_id";return function(i){return i[e]=i[e]||++t,i[e]}}(),invokeEach:function(t,e,i){var n,o;if("object"==typeof t){o=Array.prototype.slice.call(arguments,3);for(n in t)e.apply(i,[n,t[n]].concat(o));return!0}return!1},limitExecByInterval:function(t,e,i){var n,o;return function s(){var a=arguments;return n?void(o=!0):(n=!0,setTimeout(function(){n=!1,o&&(s.apply(i,a),o=!1)},e),void t.apply(i,a))}},falseFn:function(){return!1},formatNum:function(t,e){var i=Math.pow(10,e||5);return Math.round(t*i)/i},trim:function(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")},splitWords:function(t){return o.Util.trim(t).split(/\s+/)},setOptions:function(t,e){return t.options=o.extend({},t.options,e),t.options},getParamString:function(t,e,i){var n=[];for(var o in t)n.push(encodeURIComponent(i?o.toUpperCase():o)+"="+encodeURIComponent(t[o]));return(e&&-1!==e.indexOf("?")?"&":"?")+n.join("&")},template:function(t,e){return t.replace(/\{ *([\w_]+) *\}/g,function(t,n){var o=e[n];if(o===i)throw new Error("No value provided for variable "+t);return"function"==typeof o&&(o=o(e)),o})},isArray:Array.isArray||function(t){return"[object Array]"===Object.prototype.toString.call(t)},emptyImageUrl:"data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs="},function(){function e(e){var i,n,o=["webkit","moz","o","ms"];for(i=0;it;t++)n._initHooks[t].call(this)}},e},o.Class.include=function(t){o.extend(this.prototype,t)},o.Class.mergeOptions=function(t){o.extend(this.prototype.options,t)},o.Class.addInitHook=function(t){var e=Array.prototype.slice.call(arguments,1),i="function"==typeof t?t:function(){this[t].apply(this,e)};this.prototype._initHooks=this.prototype._initHooks||[],this.prototype._initHooks.push(i)};var s="_leaflet_events";o.Mixin={},o.Mixin.Events={addEventListener:function(t,e,i){if(o.Util.invokeEach(t,this.addEventListener,this,e,i))return this;var n,a,r,h,l,u,c,d=this[s]=this[s]||{},p=i&&i!==this&&o.stamp(i);for(t=o.Util.splitWords(t),n=0,a=t.length;a>n;n++)r={action:e,context:i||this},h=t[n],p?(l=h+"_idx",u=l+"_len",c=d[l]=d[l]||{},c[p]||(c[p]=[],d[u]=(d[u]||0)+1),c[p].push(r)):(d[h]=d[h]||[],d[h].push(r));return this},hasEventListeners:function(t){var e=this[s];return!!e&&(t in e&&e[t].length>0||t+"_idx"in e&&e[t+"_idx_len"]>0)},removeEventListener:function(t,e,i){if(!this[s])return this;if(!t)return this.clearAllEventListeners();if(o.Util.invokeEach(t,this.removeEventListener,this,e,i))return this;var n,a,r,h,l,u,c,d,p,_=this[s],m=i&&i!==this&&o.stamp(i);for(t=o.Util.splitWords(t),n=0,a=t.length;a>n;n++)if(r=t[n],u=r+"_idx",c=u+"_len",d=_[u],e){if(h=m&&d?d[m]:_[r]){for(l=h.length-1;l>=0;l--)h[l].action!==e||i&&h[l].context!==i||(p=h.splice(l,1),p[0].action=o.Util.falseFn);i&&d&&0===h.length&&(delete d[m],_[c]--)}}else delete _[r],delete _[u],delete _[c];return this},clearAllEventListeners:function(){return delete this[s],this},fireEvent:function(t,e){if(!this.hasEventListeners(t))return this;var i,n,a,r,h,l=o.Util.extend({},e,{type:t,target:this}),u=this[s];if(u[t])for(i=u[t].slice(),n=0,a=i.length;a>n;n++)i[n].action.call(i[n].context,l);r=u[t+"_idx"];for(h in r)if(i=r[h].slice())for(n=0,a=i.length;a>n;n++)i[n].action.call(i[n].context,l);return this},addOneTimeEventListener:function(t,e,i){if(o.Util.invokeEach(t,this.addOneTimeEventListener,this,e,i))return this;var n=o.bind(function(){this.removeEventListener(t,e,i).removeEventListener(t,n,i)},this);return this.addEventListener(t,e,i).addEventListener(t,n,i)}},o.Mixin.Events.on=o.Mixin.Events.addEventListener,o.Mixin.Events.off=o.Mixin.Events.removeEventListener,o.Mixin.Events.once=o.Mixin.Events.addOneTimeEventListener,o.Mixin.Events.fire=o.Mixin.Events.fireEvent,function(){var n="ActiveXObject"in t,s=n&&!e.addEventListener,a=navigator.userAgent.toLowerCase(),r=-1!==a.indexOf("webkit"),h=-1!==a.indexOf("chrome"),l=-1!==a.indexOf("phantom"),u=-1!==a.indexOf("android"),c=-1!==a.search("android [23]"),d=-1!==a.indexOf("gecko"),p=typeof orientation!=i+"",_=!t.PointerEvent&&t.MSPointerEvent,m=t.PointerEvent&&t.navigator.pointerEnabled||_,f="devicePixelRatio"in t&&t.devicePixelRatio>1||"matchMedia"in t&&t.matchMedia("(min-resolution:144dpi)")&&t.matchMedia("(min-resolution:144dpi)").matches,g=e.documentElement,v=n&&"transition"in g.style,y="WebKitCSSMatrix"in t&&"m11"in new t.WebKitCSSMatrix&&!c,P="MozPerspective"in g.style,L="OTransition"in g.style,x=!t.L_DISABLE_3D&&(v||y||P||L)&&!l,w=!t.L_NO_TOUCH&&!l&&(m||"ontouchstart"in t||t.DocumentTouch&&e instanceof t.DocumentTouch);o.Browser={ie:n,ielt9:s,webkit:r,gecko:d&&!r&&!t.opera&&!n,android:u,android23:c,chrome:h,ie3d:v,webkit3d:y,gecko3d:P,opera3d:L,any3d:x,mobile:p,mobileWebkit:p&&r,mobileWebkit3d:p&&y,mobileOpera:p&&t.opera,touch:w,msPointer:_,pointer:m,retina:f}}(),o.Point=function(t,e,i){this.x=i?Math.round(t):t,this.y=i?Math.round(e):e},o.Point.prototype={clone:function(){return new o.Point(this.x,this.y)},add:function(t){return this.clone()._add(o.point(t))},_add:function(t){return this.x+=t.x,this.y+=t.y,this},subtract:function(t){return this.clone()._subtract(o.point(t))},_subtract:function(t){return this.x-=t.x,this.y-=t.y,this},divideBy:function(t){return this.clone()._divideBy(t)},_divideBy:function(t){return this.x/=t,this.y/=t,this},multiplyBy:function(t){return this.clone()._multiplyBy(t)},_multiplyBy:function(t){return this.x*=t,this.y*=t,this},round:function(){return this.clone()._round()},_round:function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this},floor:function(){return this.clone()._floor()},_floor:function(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this},distanceTo:function(t){t=o.point(t);var e=t.x-this.x,i=t.y-this.y;return Math.sqrt(e*e+i*i)},equals:function(t){return t=o.point(t),t.x===this.x&&t.y===this.y},contains:function(t){return t=o.point(t),Math.abs(t.x)<=Math.abs(this.x)&&Math.abs(t.y)<=Math.abs(this.y)},toString:function(){return"Point("+o.Util.formatNum(this.x)+", "+o.Util.formatNum(this.y)+")"}},o.point=function(t,e,n){return t instanceof o.Point?t:o.Util.isArray(t)?new o.Point(t[0],t[1]):t===i||null===t?t:new o.Point(t,e,n)},o.Bounds=function(t,e){if(t)for(var i=e?[t,e]:t,n=0,o=i.length;o>n;n++)this.extend(i[n])},o.Bounds.prototype={extend:function(t){return t=o.point(t),this.min||this.max?(this.min.x=Math.min(t.x,this.min.x),this.max.x=Math.max(t.x,this.max.x),this.min.y=Math.min(t.y,this.min.y),this.max.y=Math.max(t.y,this.max.y)):(this.min=t.clone(),this.max=t.clone()),this},getCenter:function(t){return new o.Point((this.min.x+this.max.x)/2,(this.min.y+this.max.y)/2,t)},getBottomLeft:function(){return new o.Point(this.min.x,this.max.y)},getTopRight:function(){return new o.Point(this.max.x,this.min.y)},getSize:function(){return this.max.subtract(this.min)},contains:function(t){var e,i;return t="number"==typeof t[0]||t instanceof o.Point?o.point(t):o.bounds(t),t instanceof o.Bounds?(e=t.min,i=t.max):e=i=t,e.x>=this.min.x&&i.x<=this.max.x&&e.y>=this.min.y&&i.y<=this.max.y},intersects:function(t){t=o.bounds(t);var e=this.min,i=this.max,n=t.min,s=t.max,a=s.x>=e.x&&n.x<=i.x,r=s.y>=e.y&&n.y<=i.y;return a&&r},isValid:function(){return!(!this.min||!this.max)}},o.bounds=function(t,e){return!t||t instanceof o.Bounds?t:new o.Bounds(t,e)},o.Transformation=function(t,e,i,n){this._a=t,this._b=e,this._c=i,this._d=n},o.Transformation.prototype={transform:function(t,e){return this._transform(t.clone(),e)},_transform:function(t,e){return e=e||1,t.x=e*(this._a*t.x+this._b),t.y=e*(this._c*t.y+this._d),t},untransform:function(t,e){return e=e||1,new o.Point((t.x/e-this._b)/this._a,(t.y/e-this._d)/this._c)}},o.DomUtil={get:function(t){return"string"==typeof t?e.getElementById(t):t},getStyle:function(t,i){var n=t.style[i];if(!n&&t.currentStyle&&(n=t.currentStyle[i]),(!n||"auto"===n)&&e.defaultView){var o=e.defaultView.getComputedStyle(t,null);n=o?o[i]:null}return"auto"===n?null:n},getViewportOffset:function(t){var i,n=0,s=0,a=t,r=e.body,h=e.documentElement;do{if(n+=a.offsetTop||0,s+=a.offsetLeft||0,n+=parseInt(o.DomUtil.getStyle(a,"borderTopWidth"),10)||0,s+=parseInt(o.DomUtil.getStyle(a,"borderLeftWidth"),10)||0,i=o.DomUtil.getStyle(a,"position"),a.offsetParent===r&&"absolute"===i)break;if("fixed"===i){n+=r.scrollTop||h.scrollTop||0,s+=r.scrollLeft||h.scrollLeft||0;break}if("relative"===i&&!a.offsetLeft){var l=o.DomUtil.getStyle(a,"width"),u=o.DomUtil.getStyle(a,"max-width"),c=a.getBoundingClientRect();("none"!==l||"none"!==u)&&(s+=c.left+a.clientLeft),n+=c.top+(r.scrollTop||h.scrollTop||0);break}a=a.offsetParent}while(a);a=t;do{if(a===r)break;n-=a.scrollTop||0,s-=a.scrollLeft||0,a=a.parentNode}while(a);return new o.Point(s,n)},documentIsLtr:function(){return o.DomUtil._docIsLtrCached||(o.DomUtil._docIsLtrCached=!0,o.DomUtil._docIsLtr="ltr"===o.DomUtil.getStyle(e.body,"direction")),o.DomUtil._docIsLtr},create:function(t,i,n){var o=e.createElement(t);return o.className=i,n&&n.appendChild(o),o},hasClass:function(t,e){if(t.classList!==i)return t.classList.contains(e);var n=o.DomUtil._getClass(t);return n.length>0&&new RegExp("(^|\\s)"+e+"(\\s|$)").test(n)},addClass:function(t,e){if(t.classList!==i)for(var n=o.Util.splitWords(e),s=0,a=n.length;a>s;s++)t.classList.add(n[s]);else if(!o.DomUtil.hasClass(t,e)){var r=o.DomUtil._getClass(t);o.DomUtil._setClass(t,(r?r+" ":"")+e)}},removeClass:function(t,e){t.classList!==i?t.classList.remove(e):o.DomUtil._setClass(t,o.Util.trim((" "+o.DomUtil._getClass(t)+" ").replace(" "+e+" "," ")))},_setClass:function(t,e){t.className.baseVal===i?t.className=e:t.className.baseVal=e},_getClass:function(t){return t.className.baseVal===i?t.className:t.className.baseVal},setOpacity:function(t,e){if("opacity"in t.style)t.style.opacity=e;else if("filter"in t.style){var i=!1,n="DXImageTransform.Microsoft.Alpha";try{i=t.filters.item(n)}catch(o){if(1===e)return}e=Math.round(100*e),i?(i.Enabled=100!==e,i.Opacity=e):t.style.filter+=" progid:"+n+"(opacity="+e+")"}},testProp:function(t){for(var i=e.documentElement.style,n=0;ni||i===e?e:t),new o.LatLng(this.lat,i)}},o.latLng=function(t,e){return t instanceof o.LatLng?t:o.Util.isArray(t)?"number"==typeof t[0]||"string"==typeof t[0]?new o.LatLng(t[0],t[1],t[2]):null:t===i||null===t?t:"object"==typeof t&&"lat"in t?new o.LatLng(t.lat,"lng"in t?t.lng:t.lon):e===i?null:new o.LatLng(t,e)},o.LatLngBounds=function(t,e){if(t)for(var i=e?[t,e]:t,n=0,o=i.length;o>n;n++)this.extend(i[n])},o.LatLngBounds.prototype={extend:function(t){if(!t)return this;var e=o.latLng(t);return t=null!==e?e:o.latLngBounds(t),t instanceof o.LatLng?this._southWest||this._northEast?(this._southWest.lat=Math.min(t.lat,this._southWest.lat),this._southWest.lng=Math.min(t.lng,this._southWest.lng),this._northEast.lat=Math.max(t.lat,this._northEast.lat),this._northEast.lng=Math.max(t.lng,this._northEast.lng)):(this._southWest=new o.LatLng(t.lat,t.lng),this._northEast=new o.LatLng(t.lat,t.lng)):t instanceof o.LatLngBounds&&(this.extend(t._southWest),this.extend(t._northEast)),this},pad:function(t){var e=this._southWest,i=this._northEast,n=Math.abs(e.lat-i.lat)*t,s=Math.abs(e.lng-i.lng)*t;return new o.LatLngBounds(new o.LatLng(e.lat-n,e.lng-s),new o.LatLng(i.lat+n,i.lng+s))},getCenter:function(){return new o.LatLng((this._southWest.lat+this._northEast.lat)/2,(this._southWest.lng+this._northEast.lng)/2)},getSouthWest:function(){return this._southWest},getNorthEast:function(){return this._northEast},getNorthWest:function(){return new o.LatLng(this.getNorth(),this.getWest())},getSouthEast:function(){return new o.LatLng(this.getSouth(),this.getEast())},getWest:function(){return this._southWest.lng},getSouth:function(){return this._southWest.lat},getEast:function(){return this._northEast.lng},getNorth:function(){return this._northEast.lat},contains:function(t){t="number"==typeof t[0]||t instanceof o.LatLng?o.latLng(t):o.latLngBounds(t);var e,i,n=this._southWest,s=this._northEast;return t instanceof o.LatLngBounds?(e=t.getSouthWest(),i=t.getNorthEast()):e=i=t,e.lat>=n.lat&&i.lat<=s.lat&&e.lng>=n.lng&&i.lng<=s.lng},intersects:function(t){t=o.latLngBounds(t);var e=this._southWest,i=this._northEast,n=t.getSouthWest(),s=t.getNorthEast(),a=s.lat>=e.lat&&n.lat<=i.lat,r=s.lng>=e.lng&&n.lng<=i.lng;return a&&r},toBBoxString:function(){return[this.getWest(),this.getSouth(),this.getEast(),this.getNorth()].join(",")},equals:function(t){return t?(t=o.latLngBounds(t),this._southWest.equals(t.getSouthWest())&&this._northEast.equals(t.getNorthEast())):!1},isValid:function(){return!(!this._southWest||!this._northEast)}},o.latLngBounds=function(t,e){return!t||t instanceof o.LatLngBounds?t:new o.LatLngBounds(t,e)},o.Projection={},o.Projection.SphericalMercator={MAX_LATITUDE:85.0511287798,project:function(t){var e=o.LatLng.DEG_TO_RAD,i=this.MAX_LATITUDE,n=Math.max(Math.min(i,t.lat),-i),s=t.lng*e,a=n*e;return a=Math.log(Math.tan(Math.PI/4+a/2)),new o.Point(s,a)},unproject:function(t){var e=o.LatLng.RAD_TO_DEG,i=t.x*e,n=(2*Math.atan(Math.exp(t.y))-Math.PI/2)*e;return new o.LatLng(n,i)}},o.Projection.LonLat={project:function(t){return new o.Point(t.lng,t.lat)},unproject:function(t){return new o.LatLng(t.y,t.x)}},o.CRS={latLngToPoint:function(t,e){var i=this.projection.project(t),n=this.scale(e);return this.transformation._transform(i,n)},pointToLatLng:function(t,e){var i=this.scale(e),n=this.transformation.untransform(t,i);return this.projection.unproject(n)},project:function(t){return this.projection.project(t)},scale:function(t){return 256*Math.pow(2,t)},getSize:function(t){var e=this.scale(t);return o.point(e,e)}},o.CRS.Simple=o.extend({},o.CRS,{projection:o.Projection.LonLat,transformation:new o.Transformation(1,0,-1,0),scale:function(t){return Math.pow(2,t)}}),o.CRS.EPSG3857=o.extend({},o.CRS,{code:"EPSG:3857",projection:o.Projection.SphericalMercator,transformation:new o.Transformation(.5/Math.PI,.5,-.5/Math.PI,.5),project:function(t){var e=this.projection.project(t),i=6378137;return e.multiplyBy(i)}}),o.CRS.EPSG900913=o.extend({},o.CRS.EPSG3857,{code:"EPSG:900913"}),o.CRS.EPSG4326=o.extend({},o.CRS,{code:"EPSG:4326",projection:o.Projection.LonLat,transformation:new o.Transformation(1/360,.5,-1/360,.5)}),o.Map=o.Class.extend({includes:o.Mixin.Events,options:{crs:o.CRS.EPSG3857,fadeAnimation:o.DomUtil.TRANSITION&&!o.Browser.android23,trackResize:!0,markerZoomAnimation:o.DomUtil.TRANSITION&&o.Browser.any3d},initialize:function(t,e){e=o.setOptions(this,e),this._initContainer(t),this._initLayout(),this._onResize=o.bind(this._onResize,this),this._initEvents(),e.maxBounds&&this.setMaxBounds(e.maxBounds),e.center&&e.zoom!==i&&this.setView(o.latLng(e.center),e.zoom,{reset:!0}),this._handlers=[],this._layers={},this._zoomBoundLayers={},this._tileLayersNum=0,this.callInitHooks(),this._addLayers(e.layers)},setView:function(t,e){return e=e===i?this.getZoom():e,this._resetView(o.latLng(t),this._limitZoom(e)),this},setZoom:function(t,e){return this._loaded?this.setView(this.getCenter(),t,{zoom:e}):(this._zoom=this._limitZoom(t),this)},zoomIn:function(t,e){return this.setZoom(this._zoom+(t||1),e)},zoomOut:function(t,e){return this.setZoom(this._zoom-(t||1),e)},setZoomAround:function(t,e,i){var n=this.getZoomScale(e),s=this.getSize().divideBy(2),a=t instanceof o.Point?t:this.latLngToContainerPoint(t),r=a.subtract(s).multiplyBy(1-1/n),h=this.containerPointToLatLng(s.add(r));return this.setView(h,e,{zoom:i})},fitBounds:function(t,e){e=e||{},t=t.getBounds?t.getBounds():o.latLngBounds(t);var i=o.point(e.paddingTopLeft||e.padding||[0,0]),n=o.point(e.paddingBottomRight||e.padding||[0,0]),s=this.getBoundsZoom(t,!1,i.add(n));s=e.maxZoom?Math.min(e.maxZoom,s):s;var a=n.subtract(i).divideBy(2),r=this.project(t.getSouthWest(),s),h=this.project(t.getNorthEast(),s),l=this.unproject(r.add(h).divideBy(2).add(a),s);return this.setView(l,s,e)},fitWorld:function(t){return this.fitBounds([[-90,-180],[90,180]],t)},panTo:function(t,e){return this.setView(t,this._zoom,{pan:e})},panBy:function(t){return this.fire("movestart"),this._rawPanBy(o.point(t)),this.fire("move"),this.fire("moveend")},setMaxBounds:function(t){return t=o.latLngBounds(t),this.options.maxBounds=t,t?(this._loaded&&this._panInsideMaxBounds(),this.on("moveend",this._panInsideMaxBounds,this)):this.off("moveend",this._panInsideMaxBounds,this)},panInsideBounds:function(t,e){var i=this.getCenter(),n=this._limitCenter(i,this._zoom,t);return i.equals(n)?this:this.panTo(n,e)},addLayer:function(t){var e=o.stamp(t);return this._layers[e]?this:(this._layers[e]=t,!t.options||isNaN(t.options.maxZoom)&&isNaN(t.options.minZoom)||(this._zoomBoundLayers[e]=t,this._updateZoomLevels()),this.options.zoomAnimation&&o.TileLayer&&t instanceof o.TileLayer&&(this._tileLayersNum++,this._tileLayersToLoad++,t.on("load",this._onTileLayerLoad,this)),this._loaded&&this._layerAdd(t),this)},removeLayer:function(t){var e=o.stamp(t);return this._layers[e]?(this._loaded&&t.onRemove(this),delete this._layers[e],this._loaded&&this.fire("layerremove",{layer:t}),this._zoomBoundLayers[e]&&(delete this._zoomBoundLayers[e],this._updateZoomLevels()),this.options.zoomAnimation&&o.TileLayer&&t instanceof o.TileLayer&&(this._tileLayersNum--,this._tileLayersToLoad--,t.off("load",this._onTileLayerLoad,this)),this):this},hasLayer:function(t){return t?o.stamp(t)in this._layers:!1},eachLayer:function(t,e){for(var i in this._layers)t.call(e,this._layers[i]);return this},invalidateSize:function(t){if(!this._loaded)return this;t=o.extend({animate:!1,pan:!0},t===!0?{animate:!0}:t);var e=this.getSize();this._sizeChanged=!0,this._initialCenter=null;var i=this.getSize(),n=e.divideBy(2).round(),s=i.divideBy(2).round(),a=n.subtract(s);return a.x||a.y?(t.animate&&t.pan?this.panBy(a):(t.pan&&this._rawPanBy(a),this.fire("move"),t.debounceMoveend?(clearTimeout(this._sizeTimer),this._sizeTimer=setTimeout(o.bind(this.fire,this,"moveend"),200)):this.fire("moveend")),this.fire("resize",{oldSize:e,newSize:i})):this},addHandler:function(t,e){if(!e)return this;var i=this[t]=new e(this);return this._handlers.push(i),this.options[t]&&i.enable(),this},remove:function(){this._loaded&&this.fire("unload"),this._initEvents("off");try{delete this._container._leaflet}catch(t){this._container._leaflet=i}return this._clearPanes(),this._clearControlPos&&this._clearControlPos(),this._clearHandlers(),this},getCenter:function(){return this._checkIfLoaded(),this._initialCenter&&!this._moved()?this._initialCenter:this.layerPointToLatLng(this._getCenterLayerPoint())},getZoom:function(){return this._zoom},getBounds:function(){var t=this.getPixelBounds(),e=this.unproject(t.getBottomLeft()),i=this.unproject(t.getTopRight());return new o.LatLngBounds(e,i)},getMinZoom:function(){return this.options.minZoom===i?this._layersMinZoom===i?0:this._layersMinZoom:this.options.minZoom},getMaxZoom:function(){return this.options.maxZoom===i?this._layersMaxZoom===i?1/0:this._layersMaxZoom:this.options.maxZoom},getBoundsZoom:function(t,e,i){t=o.latLngBounds(t);var n,s=this.getMinZoom()-(e?1:0),a=this.getMaxZoom(),r=this.getSize(),h=t.getNorthWest(),l=t.getSouthEast(),u=!0;i=o.point(i||[0,0]);do s++,n=this.project(l,s).subtract(this.project(h,s)).add(i),u=e?n.x=s);return u&&e?null:e?s:s-1},getSize:function(){return(!this._size||this._sizeChanged)&&(this._size=new o.Point(this._container.clientWidth,this._container.clientHeight),this._sizeChanged=!1),this._size.clone()},getPixelBounds:function(){var t=this._getTopLeftPoint();return new o.Bounds(t,t.add(this.getSize()))},getPixelOrigin:function(){return this._checkIfLoaded(),this._initialTopLeftPoint},getPanes:function(){return this._panes},getContainer:function(){return this._container},getZoomScale:function(t){var e=this.options.crs;return e.scale(t)/e.scale(this._zoom)},getScaleZoom:function(t){return this._zoom+Math.log(t)/Math.LN2},project:function(t,e){return e=e===i?this._zoom:e,this.options.crs.latLngToPoint(o.latLng(t),e)},unproject:function(t,e){return e=e===i?this._zoom:e,this.options.crs.pointToLatLng(o.point(t),e)},layerPointToLatLng:function(t){var e=o.point(t).add(this.getPixelOrigin());return this.unproject(e)},latLngToLayerPoint:function(t){var e=this.project(o.latLng(t))._round();return e._subtract(this.getPixelOrigin())},containerPointToLayerPoint:function(t){return o.point(t).subtract(this._getMapPanePos())},layerPointToContainerPoint:function(t){return o.point(t).add(this._getMapPanePos())},containerPointToLatLng:function(t){var e=this.containerPointToLayerPoint(o.point(t));return this.layerPointToLatLng(e)},latLngToContainerPoint:function(t){return this.layerPointToContainerPoint(this.latLngToLayerPoint(o.latLng(t)))},mouseEventToContainerPoint:function(t){return o.DomEvent.getMousePosition(t,this._container)},mouseEventToLayerPoint:function(t){return this.containerPointToLayerPoint(this.mouseEventToContainerPoint(t))},mouseEventToLatLng:function(t){return this.layerPointToLatLng(this.mouseEventToLayerPoint(t))},_initContainer:function(t){var e=this._container=o.DomUtil.get(t);if(!e)throw new Error("Map container not found.");if(e._leaflet)throw new Error("Map container is already initialized.");e._leaflet=!0},_initLayout:function(){var t=this._container;o.DomUtil.addClass(t,"leaflet-container"+(o.Browser.touch?" leaflet-touch":"")+(o.Browser.retina?" leaflet-retina":"")+(o.Browser.ielt9?" leaflet-oldie":"")+(this.options.fadeAnimation?" leaflet-fade-anim":""));var e=o.DomUtil.getStyle(t,"position");"absolute"!==e&&"relative"!==e&&"fixed"!==e&&(t.style.position="relative"),this._initPanes(),this._initControlPos&&this._initControlPos()},_initPanes:function(){var t=this._panes={};this._mapPane=t.mapPane=this._createPane("leaflet-map-pane",this._container),this._tilePane=t.tilePane=this._createPane("leaflet-tile-pane",this._mapPane),t.objectsPane=this._createPane("leaflet-objects-pane",this._mapPane),t.shadowPane=this._createPane("leaflet-shadow-pane"),t.overlayPane=this._createPane("leaflet-overlay-pane"),t.markerPane=this._createPane("leaflet-marker-pane"),t.popupPane=this._createPane("leaflet-popup-pane");var e=" leaflet-zoom-hide";this.options.markerZoomAnimation||(o.DomUtil.addClass(t.markerPane,e),o.DomUtil.addClass(t.shadowPane,e),o.DomUtil.addClass(t.popupPane,e))},_createPane:function(t,e){return o.DomUtil.create("div",t,e||this._panes.objectsPane)},_clearPanes:function(){this._container.removeChild(this._mapPane)},_addLayers:function(t){t=t?o.Util.isArray(t)?t:[t]:[];for(var e=0,i=t.length;i>e;e++)this.addLayer(t[e])},_resetView:function(t,e,i,n){var s=this._zoom!==e;n||(this.fire("movestart"),s&&this.fire("zoomstart")),this._zoom=e,this._initialCenter=t,this._initialTopLeftPoint=this._getNewTopLeftPoint(t),i?this._initialTopLeftPoint._add(this._getMapPanePos()):o.DomUtil.setPosition(this._mapPane,new o.Point(0,0)),this._tileLayersToLoad=this._tileLayersNum;var a=!this._loaded;this._loaded=!0,this.fire("viewreset",{hard:!i}),a&&(this.fire("load"),this.eachLayer(this._layerAdd,this)),this.fire("move"),(s||n)&&this.fire("zoomend"),this.fire("moveend",{hard:!i})},_rawPanBy:function(t){o.DomUtil.setPosition(this._mapPane,this._getMapPanePos().subtract(t))},_getZoomSpan:function(){return this.getMaxZoom()-this.getMinZoom()},_updateZoomLevels:function(){var t,e=1/0,n=-(1/0),o=this._getZoomSpan();for(t in this._zoomBoundLayers){var s=this._zoomBoundLayers[t];isNaN(s.options.minZoom)||(e=Math.min(e,s.options.minZoom)),isNaN(s.options.maxZoom)||(n=Math.max(n,s.options.maxZoom))}t===i?this._layersMaxZoom=this._layersMinZoom=i:(this._layersMaxZoom=n,this._layersMinZoom=e),o!==this._getZoomSpan()&&this.fire("zoomlevelschange")},_panInsideMaxBounds:function(){this.panInsideBounds(this.options.maxBounds)},_checkIfLoaded:function(){if(!this._loaded)throw new Error("Set map center and zoom first.")},_initEvents:function(e){if(o.DomEvent){e=e||"on",o.DomEvent[e](this._container,"click",this._onMouseClick,this);var i,n,s=["dblclick","mousedown","mouseup","mouseenter","mouseleave","mousemove","contextmenu"];for(i=0,n=s.length;n>i;i++)o.DomEvent[e](this._container,s[i],this._fireMouseEvent,this);this.options.trackResize&&o.DomEvent[e](t,"resize",this._onResize,this)}},_onResize:function(){o.Util.cancelAnimFrame(this._resizeRequest),this._resizeRequest=o.Util.requestAnimFrame(function(){this.invalidateSize({debounceMoveend:!0})},this,!1,this._container)},_onMouseClick:function(t){!this._loaded||!t._simulated&&(this.dragging&&this.dragging.moved()||this.boxZoom&&this.boxZoom.moved())||o.DomEvent._skipped(t)||(this.fire("preclick"),this._fireMouseEvent(t))},_fireMouseEvent:function(t){if(this._loaded&&!o.DomEvent._skipped(t)){var e=t.type;if(e="mouseenter"===e?"mouseover":"mouseleave"===e?"mouseout":e,this.hasEventListeners(e)){"contextmenu"===e&&o.DomEvent.preventDefault(t);var i=this.mouseEventToContainerPoint(t),n=this.containerPointToLayerPoint(i),s=this.layerPointToLatLng(n);this.fire(e,{latlng:s,layerPoint:n,containerPoint:i,originalEvent:t})}}},_onTileLayerLoad:function(){this._tileLayersToLoad--,this._tileLayersNum&&!this._tileLayersToLoad&&this.fire("tilelayersload")},_clearHandlers:function(){for(var t=0,e=this._handlers.length;e>t;t++)this._handlers[t].disable()},whenReady:function(t,e){return this._loaded?t.call(e||this,this):this.on("load",t,e),this},_layerAdd:function(t){t.onAdd(this),this.fire("layeradd",{layer:t})},_getMapPanePos:function(){return o.DomUtil.getPosition(this._mapPane)},_moved:function(){var t=this._getMapPanePos();return t&&!t.equals([0,0])},_getTopLeftPoint:function(){return this.getPixelOrigin().subtract(this._getMapPanePos())},_getNewTopLeftPoint:function(t,e){var i=this.getSize()._divideBy(2);return this.project(t,e)._subtract(i)._round()},_latLngToNewLayerPoint:function(t,e,i){var n=this._getNewTopLeftPoint(i,e).add(this._getMapPanePos());return this.project(t,e)._subtract(n)},_getCenterLayerPoint:function(){return this.containerPointToLayerPoint(this.getSize()._divideBy(2))},_getCenterOffset:function(t){return this.latLngToLayerPoint(t).subtract(this._getCenterLayerPoint())},_limitCenter:function(t,e,i){if(!i)return t;var n=this.project(t,e),s=this.getSize().divideBy(2),a=new o.Bounds(n.subtract(s),n.add(s)),r=this._getBoundsOffset(a,i,e);return this.unproject(n.add(r),e)},_limitOffset:function(t,e){if(!e)return t;var i=this.getPixelBounds(),n=new o.Bounds(i.min.add(t),i.max.add(t));return t.add(this._getBoundsOffset(n,e))},_getBoundsOffset:function(t,e,i){var n=this.project(e.getNorthWest(),i).subtract(t.min),s=this.project(e.getSouthEast(),i).subtract(t.max),a=this._rebound(n.x,-s.x),r=this._rebound(n.y,-s.y);return new o.Point(a,r)},_rebound:function(t,e){return t+e>0?Math.round(t-e)/2:Math.max(0,Math.ceil(t))-Math.max(0,Math.floor(e))},_limitZoom:function(t){var e=this.getMinZoom(),i=this.getMaxZoom();return Math.max(e,Math.min(i,t))}}),o.map=function(t,e){return new o.Map(t,e)},o.Projection.Mercator={MAX_LATITUDE:85.0840591556,R_MINOR:6356752.314245179,R_MAJOR:6378137,project:function(t){var e=o.LatLng.DEG_TO_RAD,i=this.MAX_LATITUDE,n=Math.max(Math.min(i,t.lat),-i),s=this.R_MAJOR,a=this.R_MINOR,r=t.lng*e*s,h=n*e,l=a/s,u=Math.sqrt(1-l*l),c=u*Math.sin(h);c=Math.pow((1-c)/(1+c),.5*u);var d=Math.tan(.5*(.5*Math.PI-h))/c;return h=-s*Math.log(d),new o.Point(r,h)},unproject:function(t){for(var e,i=o.LatLng.RAD_TO_DEG,n=this.R_MAJOR,s=this.R_MINOR,a=t.x*i/n,r=s/n,h=Math.sqrt(1-r*r),l=Math.exp(-t.y/n),u=Math.PI/2-2*Math.atan(l),c=15,d=1e-7,p=c,_=.1;Math.abs(_)>d&&--p>0;)e=h*Math.sin(u),_=Math.PI/2-2*Math.atan(l*Math.pow((1-e)/(1+e),.5*h))-u,u+=_;return new o.LatLng(u*i,a)}},o.CRS.EPSG3395=o.extend({},o.CRS,{code:"EPSG:3395",projection:o.Projection.Mercator, -transformation:function(){var t=o.Projection.Mercator,e=t.R_MAJOR,i=.5/(Math.PI*e);return new o.Transformation(i,.5,-i,.5)}()}),o.TileLayer=o.Class.extend({includes:o.Mixin.Events,options:{minZoom:0,maxZoom:18,tileSize:256,subdomains:"abc",errorTileUrl:"",attribution:"",zoomOffset:0,opacity:1,unloadInvisibleTiles:o.Browser.mobile,updateWhenIdle:o.Browser.mobile},initialize:function(t,e){e=o.setOptions(this,e),e.detectRetina&&o.Browser.retina&&e.maxZoom>0&&(e.tileSize=Math.floor(e.tileSize/2),e.zoomOffset++,e.minZoom>0&&e.minZoom--,this.options.maxZoom--),e.bounds&&(e.bounds=o.latLngBounds(e.bounds)),this._url=t;var i=this.options.subdomains;"string"==typeof i&&(this.options.subdomains=i.split(""))},onAdd:function(t){this._map=t,this._animated=t._zoomAnimated,this._initContainer(),t.on({viewreset:this._reset,moveend:this._update},this),this._animated&&t.on({zoomanim:this._animateZoom,zoomend:this._endZoomAnim},this),this.options.updateWhenIdle||(this._limitedUpdate=o.Util.limitExecByInterval(this._update,150,this),t.on("move",this._limitedUpdate,this)),this._reset(),this._update()},addTo:function(t){return t.addLayer(this),this},onRemove:function(t){this._container.parentNode.removeChild(this._container),t.off({viewreset:this._reset,moveend:this._update},this),this._animated&&t.off({zoomanim:this._animateZoom,zoomend:this._endZoomAnim},this),this.options.updateWhenIdle||t.off("move",this._limitedUpdate,this),this._container=null,this._map=null},bringToFront:function(){var t=this._map._panes.tilePane;return this._container&&(t.appendChild(this._container),this._setAutoZIndex(t,Math.max)),this},bringToBack:function(){var t=this._map._panes.tilePane;return this._container&&(t.insertBefore(this._container,t.firstChild),this._setAutoZIndex(t,Math.min)),this},getAttribution:function(){return this.options.attribution},getContainer:function(){return this._container},setOpacity:function(t){return this.options.opacity=t,this._map&&this._updateOpacity(),this},setZIndex:function(t){return this.options.zIndex=t,this._updateZIndex(),this},setUrl:function(t,e){return this._url=t,e||this.redraw(),this},redraw:function(){return this._map&&(this._reset({hard:!0}),this._update()),this},_updateZIndex:function(){this._container&&this.options.zIndex!==i&&(this._container.style.zIndex=this.options.zIndex)},_setAutoZIndex:function(t,e){var i,n,o,s=t.children,a=-e(1/0,-(1/0));for(n=0,o=s.length;o>n;n++)s[n]!==this._container&&(i=parseInt(s[n].style.zIndex,10),isNaN(i)||(a=e(a,i)));this.options.zIndex=this._container.style.zIndex=(isFinite(a)?a:0)+e(1,-1)},_updateOpacity:function(){var t,e=this._tiles;if(o.Browser.ielt9)for(t in e)o.DomUtil.setOpacity(e[t],this.options.opacity);else o.DomUtil.setOpacity(this._container,this.options.opacity)},_initContainer:function(){var t=this._map._panes.tilePane;if(!this._container){if(this._container=o.DomUtil.create("div","leaflet-layer"),this._updateZIndex(),this._animated){var e="leaflet-tile-container";this._bgBuffer=o.DomUtil.create("div",e,this._container),this._tileContainer=o.DomUtil.create("div",e,this._container)}else this._tileContainer=this._container;t.appendChild(this._container),this.options.opacity<1&&this._updateOpacity()}},_reset:function(t){for(var e in this._tiles)this.fire("tileunload",{tile:this._tiles[e]});this._tiles={},this._tilesToLoad=0,this.options.reuseTiles&&(this._unusedTiles=[]),this._tileContainer.innerHTML="",this._animated&&t&&t.hard&&this._clearBgBuffer(),this._initContainer()},_getTileSize:function(){var t=this._map,e=t.getZoom()+this.options.zoomOffset,i=this.options.maxNativeZoom,n=this.options.tileSize;return i&&e>i&&(n=Math.round(t.getZoomScale(e)/t.getZoomScale(i)*n)),n},_update:function(){if(this._map){var t=this._map,e=t.getPixelBounds(),i=t.getZoom(),n=this._getTileSize();if(!(i>this.options.maxZoom||in;n++)this._addTile(a[n],l);this._tileContainer.appendChild(l)}},_tileShouldBeLoaded:function(t){if(t.x+":"+t.y in this._tiles)return!1;var e=this.options;if(!e.continuousWorld){var i=this._getWrapTileNum();if(e.noWrap&&(t.x<0||t.x>=i.x)||t.y<0||t.y>=i.y)return!1}if(e.bounds){var n=this._getTileSize(),o=t.multiplyBy(n),s=o.add([n,n]),a=this._map.unproject(o),r=this._map.unproject(s);if(e.continuousWorld||e.noWrap||(a=a.wrap(),r=r.wrap()),!e.bounds.intersects([a,r]))return!1}return!0},_removeOtherTiles:function(t){var e,i,n,o;for(o in this._tiles)e=o.split(":"),i=parseInt(e[0],10),n=parseInt(e[1],10),(it.max.x||nt.max.y)&&this._removeTile(o)},_removeTile:function(t){var e=this._tiles[t];this.fire("tileunload",{tile:e,url:e.src}),this.options.reuseTiles?(o.DomUtil.removeClass(e,"leaflet-tile-loaded"),this._unusedTiles.push(e)):e.parentNode===this._tileContainer&&this._tileContainer.removeChild(e),o.Browser.android||(e.onload=null,e.src=o.Util.emptyImageUrl),delete this._tiles[t]},_addTile:function(t,e){var i=this._getTilePos(t),n=this._getTile();o.DomUtil.setPosition(n,i,o.Browser.chrome),this._tiles[t.x+":"+t.y]=n,this._loadTile(n,t),n.parentNode!==this._tileContainer&&e.appendChild(n)},_getZoomForUrl:function(){var t=this.options,e=this._map.getZoom();return t.zoomReverse&&(e=t.maxZoom-e),e+=t.zoomOffset,t.maxNativeZoom?Math.min(e,t.maxNativeZoom):e},_getTilePos:function(t){var e=this._map.getPixelOrigin(),i=this._getTileSize();return t.multiplyBy(i).subtract(e)},getTileUrl:function(t){return o.Util.template(this._url,o.extend({s:this._getSubdomain(t),z:t.z,x:t.x,y:t.y},this.options))},_getWrapTileNum:function(){var t=this._map.options.crs,e=t.getSize(this._map.getZoom());return e.divideBy(this._getTileSize())._floor()},_adjustTilePoint:function(t){var e=this._getWrapTileNum();this.options.continuousWorld||this.options.noWrap||(t.x=(t.x%e.x+e.x)%e.x),this.options.tms&&(t.y=e.y-t.y-1),t.z=this._getZoomForUrl()},_getSubdomain:function(t){var e=Math.abs(t.x+t.y)%this.options.subdomains.length;return this.options.subdomains[e]},_getTile:function(){if(this.options.reuseTiles&&this._unusedTiles.length>0){var t=this._unusedTiles.pop();return this._resetTile(t),t}return this._createTile()},_resetTile:function(){},_createTile:function(){var t=o.DomUtil.create("img","leaflet-tile");return t.style.width=t.style.height=this._getTileSize()+"px",t.galleryimg="no",t.onselectstart=t.onmousemove=o.Util.falseFn,o.Browser.ielt9&&this.options.opacity!==i&&o.DomUtil.setOpacity(t,this.options.opacity),o.Browser.mobileWebkit3d&&(t.style.WebkitBackfaceVisibility="hidden"),t},_loadTile:function(t,e){t._layer=this,t.onload=this._tileOnLoad,t.onerror=this._tileOnError,this._adjustTilePoint(e),t.src=this.getTileUrl(e),this.fire("tileloadstart",{tile:t,url:t.src})},_tileLoaded:function(){this._tilesToLoad--,this._animated&&o.DomUtil.addClass(this._tileContainer,"leaflet-zoom-animated"),this._tilesToLoad||(this.fire("load"),this._animated&&(clearTimeout(this._clearBgBufferTimer),this._clearBgBufferTimer=setTimeout(o.bind(this._clearBgBuffer,this),500)))},_tileOnLoad:function(){var t=this._layer;this.src!==o.Util.emptyImageUrl&&(o.DomUtil.addClass(this,"leaflet-tile-loaded"),t.fire("tileload",{tile:this,url:this.src})),t._tileLoaded()},_tileOnError:function(){var t=this._layer;t.fire("tileerror",{tile:this,url:this.src});var e=t.options.errorTileUrl;e&&(this.src=e),t._tileLoaded()}}),o.tileLayer=function(t,e){return new o.TileLayer(t,e)},o.TileLayer.WMS=o.TileLayer.extend({defaultWmsParams:{service:"WMS",request:"GetMap",version:"1.1.1",layers:"",styles:"",format:"image/jpeg",transparent:!1},initialize:function(t,e){this._url=t;var i=o.extend({},this.defaultWmsParams),n=e.tileSize||this.options.tileSize;e.detectRetina&&o.Browser.retina?i.width=i.height=2*n:i.width=i.height=n;for(var s in e)this.options.hasOwnProperty(s)||"crs"===s||(i[s]=e[s]);this.wmsParams=i,o.setOptions(this,e)},onAdd:function(t){this._crs=this.options.crs||t.options.crs,this._wmsVersion=parseFloat(this.wmsParams.version);var e=this._wmsVersion>=1.3?"crs":"srs";this.wmsParams[e]=this._crs.code,o.TileLayer.prototype.onAdd.call(this,t)},getTileUrl:function(t){var e=this._map,i=this.options.tileSize,n=t.multiplyBy(i),s=n.add([i,i]),a=this._crs.project(e.unproject(n,t.z)),r=this._crs.project(e.unproject(s,t.z)),h=this._wmsVersion>=1.3&&this._crs===o.CRS.EPSG4326?[r.y,a.x,a.y,r.x].join(","):[a.x,r.y,r.x,a.y].join(","),l=o.Util.template(this._url,{s:this._getSubdomain(t)});return l+o.Util.getParamString(this.wmsParams,l,!0)+"&BBOX="+h},setParams:function(t,e){return o.extend(this.wmsParams,t),e||this.redraw(),this}}),o.tileLayer.wms=function(t,e){return new o.TileLayer.WMS(t,e)},o.TileLayer.Canvas=o.TileLayer.extend({options:{async:!1},initialize:function(t){o.setOptions(this,t)},redraw:function(){this._map&&(this._reset({hard:!0}),this._update());for(var t in this._tiles)this._redrawTile(this._tiles[t]);return this},_redrawTile:function(t){this.drawTile(t,t._tilePoint,this._map._zoom)},_createTile:function(){var t=o.DomUtil.create("canvas","leaflet-tile");return t.width=t.height=this.options.tileSize,t.onselectstart=t.onmousemove=o.Util.falseFn,t},_loadTile:function(t,e){t._layer=this,t._tilePoint=e,this._redrawTile(t),this.options.async||this.tileDrawn(t)},drawTile:function(){},tileDrawn:function(t){this._tileOnLoad.call(t)}}),o.tileLayer.canvas=function(t){return new o.TileLayer.Canvas(t)},o.ImageOverlay=o.Class.extend({includes:o.Mixin.Events,options:{opacity:1},initialize:function(t,e,i){this._url=t,this._bounds=o.latLngBounds(e),o.setOptions(this,i)},onAdd:function(t){this._map=t,this._image||this._initImage(),t._panes.overlayPane.appendChild(this._image),t.on("viewreset",this._reset,this),t.options.zoomAnimation&&o.Browser.any3d&&t.on("zoomanim",this._animateZoom,this),this._reset()},onRemove:function(t){t.getPanes().overlayPane.removeChild(this._image),t.off("viewreset",this._reset,this),t.options.zoomAnimation&&t.off("zoomanim",this._animateZoom,this)},addTo:function(t){return t.addLayer(this),this},setOpacity:function(t){return this.options.opacity=t,this._updateOpacity(),this},bringToFront:function(){return this._image&&this._map._panes.overlayPane.appendChild(this._image),this},bringToBack:function(){var t=this._map._panes.overlayPane;return this._image&&t.insertBefore(this._image,t.firstChild),this},setUrl:function(t){this._url=t,this._image.src=this._url},getAttribution:function(){return this.options.attribution},_initImage:function(){this._image=o.DomUtil.create("img","leaflet-image-layer"),this._map.options.zoomAnimation&&o.Browser.any3d?o.DomUtil.addClass(this._image,"leaflet-zoom-animated"):o.DomUtil.addClass(this._image,"leaflet-zoom-hide"),this._updateOpacity(),o.extend(this._image,{galleryimg:"no",onselectstart:o.Util.falseFn,onmousemove:o.Util.falseFn,onload:o.bind(this._onImageLoad,this),src:this._url})},_animateZoom:function(t){var e=this._map,i=this._image,n=e.getZoomScale(t.zoom),s=this._bounds.getNorthWest(),a=this._bounds.getSouthEast(),r=e._latLngToNewLayerPoint(s,t.zoom,t.center),h=e._latLngToNewLayerPoint(a,t.zoom,t.center)._subtract(r),l=r._add(h._multiplyBy(.5*(1-1/n)));i.style[o.DomUtil.TRANSFORM]=o.DomUtil.getTranslateString(l)+" scale("+n+") "},_reset:function(){var t=this._image,e=this._map.latLngToLayerPoint(this._bounds.getNorthWest()),i=this._map.latLngToLayerPoint(this._bounds.getSouthEast())._subtract(e);o.DomUtil.setPosition(t,e),t.style.width=i.x+"px",t.style.height=i.y+"px"},_onImageLoad:function(){this.fire("load")},_updateOpacity:function(){o.DomUtil.setOpacity(this._image,this.options.opacity)}}),o.imageOverlay=function(t,e,i){return new o.ImageOverlay(t,e,i)},o.Icon=o.Class.extend({options:{className:""},initialize:function(t){o.setOptions(this,t)},createIcon:function(t){return this._createIcon("icon",t)},createShadow:function(t){return this._createIcon("shadow",t)},_createIcon:function(t,e){var i=this._getIconUrl(t);if(!i){if("icon"===t)throw new Error("iconUrl not set in Icon options (see the docs).");return null}var n;return n=e&&"IMG"===e.tagName?this._createImg(i,e):this._createImg(i),this._setIconStyles(n,t),n},_setIconStyles:function(t,e){var i,n=this.options,s=o.point(n[e+"Size"]);i="shadow"===e?o.point(n.shadowAnchor||n.iconAnchor):o.point(n.iconAnchor),!i&&s&&(i=s.divideBy(2,!0)),t.className="leaflet-marker-"+e+" "+n.className,i&&(t.style.marginLeft=-i.x+"px",t.style.marginTop=-i.y+"px"),s&&(t.style.width=s.x+"px",t.style.height=s.y+"px")},_createImg:function(t,i){return i=i||e.createElement("img"),i.src=t,i},_getIconUrl:function(t){return o.Browser.retina&&this.options[t+"RetinaUrl"]?this.options[t+"RetinaUrl"]:this.options[t+"Url"]}}),o.icon=function(t){return new o.Icon(t)},o.Icon.Default=o.Icon.extend({options:{iconSize:[25,41],iconAnchor:[12,41],popupAnchor:[1,-34],shadowSize:[41,41]},_getIconUrl:function(t){var e=t+"Url";if(this.options[e])return this.options[e];o.Browser.retina&&"icon"===t&&(t+="-2x");var i=o.Icon.Default.imagePath;if(!i)throw new Error("Couldn't autodetect L.Icon.Default.imagePath, set it manually.");return i+"/marker-"+t+".png"}}),o.Icon.Default.imagePath=function(){var t,i,n,o,s,a=e.getElementsByTagName("script"),r=/[\/^]leaflet[\-\._]?([\w\-\._]*)\.js\??/;for(t=0,i=a.length;i>t;t++)if(n=a[t].src,o=n.match(r))return s=n.split(r)[0],(s?s+"/":"")+"images"}(),o.Marker=o.Class.extend({includes:o.Mixin.Events,options:{icon:new o.Icon.Default,title:"",alt:"",clickable:!0,draggable:!1,keyboard:!0,zIndexOffset:0,opacity:1,riseOnHover:!1,riseOffset:250},initialize:function(t,e){o.setOptions(this,e),this._latlng=o.latLng(t)},onAdd:function(t){this._map=t,t.on("viewreset",this.update,this),this._initIcon(),this.update(),this.fire("add"),t.options.zoomAnimation&&t.options.markerZoomAnimation&&t.on("zoomanim",this._animateZoom,this)},addTo:function(t){return t.addLayer(this),this},onRemove:function(t){this.dragging&&this.dragging.disable(),this._removeIcon(),this._removeShadow(),this.fire("remove"),t.off({viewreset:this.update,zoomanim:this._animateZoom},this),this._map=null},getLatLng:function(){return this._latlng},setLatLng:function(t){return this._latlng=o.latLng(t),this.update(),this.fire("move",{latlng:this._latlng})},setZIndexOffset:function(t){return this.options.zIndexOffset=t,this.update(),this},setIcon:function(t){return this.options.icon=t,this._map&&(this._initIcon(),this.update()),this._popup&&this.bindPopup(this._popup),this},update:function(){return this._icon&&this._setPos(this._map.latLngToLayerPoint(this._latlng).round()),this},_initIcon:function(){var t=this.options,e=this._map,i=e.options.zoomAnimation&&e.options.markerZoomAnimation,n=i?"leaflet-zoom-animated":"leaflet-zoom-hide",s=t.icon.createIcon(this._icon),a=!1;s!==this._icon&&(this._icon&&this._removeIcon(),a=!0,t.title&&(s.title=t.title),t.alt&&(s.alt=t.alt)),o.DomUtil.addClass(s,n),t.keyboard&&(s.tabIndex="0"),this._icon=s,this._initInteraction(),t.riseOnHover&&o.DomEvent.on(s,"mouseover",this._bringToFront,this).on(s,"mouseout",this._resetZIndex,this);var r=t.icon.createShadow(this._shadow),h=!1;r!==this._shadow&&(this._removeShadow(),h=!0),r&&o.DomUtil.addClass(r,n),this._shadow=r,t.opacity<1&&this._updateOpacity();var l=this._map._panes;a&&l.markerPane.appendChild(this._icon),r&&h&&l.shadowPane.appendChild(this._shadow)},_removeIcon:function(){this.options.riseOnHover&&o.DomEvent.off(this._icon,"mouseover",this._bringToFront).off(this._icon,"mouseout",this._resetZIndex),this._map._panes.markerPane.removeChild(this._icon),this._icon=null},_removeShadow:function(){this._shadow&&this._map._panes.shadowPane.removeChild(this._shadow),this._shadow=null},_setPos:function(t){o.DomUtil.setPosition(this._icon,t),this._shadow&&o.DomUtil.setPosition(this._shadow,t),this._zIndex=t.y+this.options.zIndexOffset,this._resetZIndex()},_updateZIndex:function(t){this._icon.style.zIndex=this._zIndex+t},_animateZoom:function(t){var e=this._map._latLngToNewLayerPoint(this._latlng,t.zoom,t.center).round();this._setPos(e)},_initInteraction:function(){if(this.options.clickable){var t=this._icon,e=["dblclick","mousedown","mouseover","mouseout","contextmenu"];o.DomUtil.addClass(t,"leaflet-clickable"),o.DomEvent.on(t,"click",this._onMouseClick,this),o.DomEvent.on(t,"keypress",this._onKeyPress,this);for(var i=0;is?(e.height=s+"px",o.DomUtil.addClass(t,a)):o.DomUtil.removeClass(t,a),this._containerWidth=this._container.offsetWidth},_updatePosition:function(){if(this._map){var t=this._map.latLngToLayerPoint(this._latlng),e=this._animated,i=o.point(this.options.offset);e&&o.DomUtil.setPosition(this._container,t),this._containerBottom=-i.y-(e?0:t.y),this._containerLeft=-Math.round(this._containerWidth/2)+i.x+(e?0:t.x),this._container.style.bottom=this._containerBottom+"px",this._container.style.left=this._containerLeft+"px"}},_zoomAnimation:function(t){var e=this._map._latLngToNewLayerPoint(this._latlng,t.zoom,t.center);o.DomUtil.setPosition(this._container,e)},_adjustPan:function(){if(this.options.autoPan){var t=this._map,e=this._container.offsetHeight,i=this._containerWidth,n=new o.Point(this._containerLeft,-e-this._containerBottom);this._animated&&n._add(o.DomUtil.getPosition(this._container));var s=t.layerPointToContainerPoint(n),a=o.point(this.options.autoPanPadding),r=o.point(this.options.autoPanPaddingTopLeft||a),h=o.point(this.options.autoPanPaddingBottomRight||a),l=t.getSize(),u=0,c=0;s.x+i+h.x>l.x&&(u=s.x+i-l.x+h.x),s.x-u-r.x<0&&(u=s.x-r.x),s.y+e+h.y>l.y&&(c=s.y+e-l.y+h.y),s.y-c-r.y<0&&(c=s.y-r.y),(u||c)&&t.fire("autopanstart").panBy([u,c])}},_onCloseButtonClick:function(t){this._close(),o.DomEvent.stop(t)}}),o.popup=function(t,e){return new o.Popup(t,e)},o.Map.include({openPopup:function(t,e,i){if(this.closePopup(),!(t instanceof o.Popup)){var n=t;t=new o.Popup(i).setLatLng(e).setContent(n)}return t._isOpen=!0,this._popup=t,this.addLayer(t)},closePopup:function(t){return t&&t!==this._popup||(t=this._popup,this._popup=null),t&&(this.removeLayer(t),t._isOpen=!1),this}}),o.Marker.include({openPopup:function(){return this._popup&&this._map&&!this._map.hasLayer(this._popup)&&(this._popup.setLatLng(this._latlng),this._map.openPopup(this._popup)),this},closePopup:function(){return this._popup&&this._popup._close(),this},togglePopup:function(){return this._popup&&(this._popup._isOpen?this.closePopup():this.openPopup()),this},bindPopup:function(t,e){var i=o.point(this.options.icon.options.popupAnchor||[0,0]);return i=i.add(o.Popup.prototype.options.offset),e&&e.offset&&(i=i.add(e.offset)),e=o.extend({offset:i},e),this._popupHandlersAdded||(this.on("click",this.togglePopup,this).on("remove",this.closePopup,this).on("move",this._movePopup,this),this._popupHandlersAdded=!0),t instanceof o.Popup?(o.setOptions(t,e),this._popup=t,t._source=this):this._popup=new o.Popup(e,this).setContent(t),this},setPopupContent:function(t){return this._popup&&this._popup.setContent(t),this},unbindPopup:function(){return this._popup&&(this._popup=null,this.off("click",this.togglePopup,this).off("remove",this.closePopup,this).off("move",this._movePopup,this),this._popupHandlersAdded=!1),this},getPopup:function(){return this._popup},_movePopup:function(t){this._popup.setLatLng(t.latlng)}}),o.LayerGroup=o.Class.extend({initialize:function(t){this._layers={};var e,i;if(t)for(e=0,i=t.length;i>e;e++)this.addLayer(t[e])},addLayer:function(t){var e=this.getLayerId(t);return this._layers[e]=t,this._map&&this._map.addLayer(t),this},removeLayer:function(t){var e=t in this._layers?t:this.getLayerId(t);return this._map&&this._layers[e]&&this._map.removeLayer(this._layers[e]),delete this._layers[e],this},hasLayer:function(t){return t?t in this._layers||this.getLayerId(t)in this._layers:!1},clearLayers:function(){return this.eachLayer(this.removeLayer,this),this},invoke:function(t){var e,i,n=Array.prototype.slice.call(arguments,1);for(e in this._layers)i=this._layers[e],i[t]&&i[t].apply(i,n);return this},onAdd:function(t){this._map=t,this.eachLayer(t.addLayer,t)},onRemove:function(t){this.eachLayer(t.removeLayer,t),this._map=null},addTo:function(t){return t.addLayer(this),this},eachLayer:function(t,e){for(var i in this._layers)t.call(e,this._layers[i]);return this},getLayer:function(t){return this._layers[t]},getLayers:function(){var t=[];for(var e in this._layers)t.push(this._layers[e]);return t},setZIndex:function(t){return this.invoke("setZIndex",t)},getLayerId:function(t){return o.stamp(t)}}),o.layerGroup=function(t){return new o.LayerGroup(t)},o.FeatureGroup=o.LayerGroup.extend({includes:o.Mixin.Events,statics:{EVENTS:"click dblclick mouseover mouseout mousemove contextmenu popupopen popupclose"},addLayer:function(t){return this.hasLayer(t)?this:("on"in t&&t.on(o.FeatureGroup.EVENTS,this._propagateEvent,this),o.LayerGroup.prototype.addLayer.call(this,t),this._popupContent&&t.bindPopup&&t.bindPopup(this._popupContent,this._popupOptions),this.fire("layeradd",{layer:t}))},removeLayer:function(t){return this.hasLayer(t)?(t in this._layers&&(t=this._layers[t]),"off"in t&&t.off(o.FeatureGroup.EVENTS,this._propagateEvent,this),o.LayerGroup.prototype.removeLayer.call(this,t),this._popupContent&&this.invoke("unbindPopup"),this.fire("layerremove",{layer:t})):this},bindPopup:function(t,e){return this._popupContent=t,this._popupOptions=e,this.invoke("bindPopup",t,e)},openPopup:function(t){for(var e in this._layers){this._layers[e].openPopup(t);break}return this},setStyle:function(t){return this.invoke("setStyle",t)},bringToFront:function(){return this.invoke("bringToFront")},bringToBack:function(){return this.invoke("bringToBack")},getBounds:function(){var t=new o.LatLngBounds;return this.eachLayer(function(e){t.extend(e instanceof o.Marker?e.getLatLng():e.getBounds())}),t},_propagateEvent:function(t){t=o.extend({layer:t.target,target:this},t),this.fire(t.type,t)}}),o.featureGroup=function(t){return new o.FeatureGroup(t)},o.Path=o.Class.extend({includes:[o.Mixin.Events],statics:{CLIP_PADDING:function(){var e=o.Browser.mobile?1280:2e3,i=(e/Math.max(t.outerWidth,t.outerHeight)-1)/2;return Math.max(0,Math.min(.5,i))}()},options:{stroke:!0,color:"#0033ff",dashArray:null,lineCap:null,lineJoin:null,weight:5,opacity:.5,fill:!1,fillColor:null,fillOpacity:.2,clickable:!0},initialize:function(t){o.setOptions(this,t)},onAdd:function(t){this._map=t,this._container||(this._initElements(),this._initEvents()),this.projectLatlngs(),this._updatePath(),this._container&&this._map._pathRoot.appendChild(this._container),this.fire("add"),t.on({viewreset:this.projectLatlngs,moveend:this._updatePath},this)},addTo:function(t){return t.addLayer(this),this},onRemove:function(t){t._pathRoot.removeChild(this._container),this.fire("remove"),this._map=null,o.Browser.vml&&(this._container=null,this._stroke=null,this._fill=null),t.off({viewreset:this.projectLatlngs,moveend:this._updatePath},this)},projectLatlngs:function(){},setStyle:function(t){return o.setOptions(this,t),this._container&&this._updateStyle(),this},redraw:function(){return this._map&&(this.projectLatlngs(),this._updatePath()),this}}),o.Map.include({_updatePathViewport:function(){var t=o.Path.CLIP_PADDING,e=this.getSize(),i=o.DomUtil.getPosition(this._mapPane),n=i.multiplyBy(-1)._subtract(e.multiplyBy(t)._round()),s=n.add(e.multiplyBy(1+2*t)._round());this._pathViewport=new o.Bounds(n,s)}}),o.Path.SVG_NS="http://www.w3.org/2000/svg",o.Browser.svg=!(!e.createElementNS||!e.createElementNS(o.Path.SVG_NS,"svg").createSVGRect),o.Path=o.Path.extend({statics:{SVG:o.Browser.svg},bringToFront:function(){var t=this._map._pathRoot,e=this._container;return e&&t.lastChild!==e&&t.appendChild(e),this},bringToBack:function(){var t=this._map._pathRoot,e=this._container,i=t.firstChild;return e&&i!==e&&t.insertBefore(e,i),this},getPathString:function(){},_createElement:function(t){return e.createElementNS(o.Path.SVG_NS,t)},_initElements:function(){this._map._initPathRoot(),this._initPath(),this._initStyle()},_initPath:function(){this._container=this._createElement("g"),this._path=this._createElement("path"),this.options.className&&o.DomUtil.addClass(this._path,this.options.className),this._container.appendChild(this._path)},_initStyle:function(){this.options.stroke&&(this._path.setAttribute("stroke-linejoin","round"),this._path.setAttribute("stroke-linecap","round")),this.options.fill&&this._path.setAttribute("fill-rule","evenodd"),this.options.pointerEvents&&this._path.setAttribute("pointer-events",this.options.pointerEvents),this.options.clickable||this.options.pointerEvents||this._path.setAttribute("pointer-events","none"),this._updateStyle()},_updateStyle:function(){this.options.stroke?(this._path.setAttribute("stroke",this.options.color),this._path.setAttribute("stroke-opacity",this.options.opacity),this._path.setAttribute("stroke-width",this.options.weight),this.options.dashArray?this._path.setAttribute("stroke-dasharray",this.options.dashArray):this._path.removeAttribute("stroke-dasharray"),this.options.lineCap&&this._path.setAttribute("stroke-linecap",this.options.lineCap),this.options.lineJoin&&this._path.setAttribute("stroke-linejoin",this.options.lineJoin)):this._path.setAttribute("stroke","none"),this.options.fill?(this._path.setAttribute("fill",this.options.fillColor||this.options.color),this._path.setAttribute("fill-opacity",this.options.fillOpacity)):this._path.setAttribute("fill","none")},_updatePath:function(){var t=this.getPathString();t||(t="M0 0"),this._path.setAttribute("d",t)},_initEvents:function(){if(this.options.clickable){(o.Browser.svg||!o.Browser.vml)&&o.DomUtil.addClass(this._path,"leaflet-clickable"),o.DomEvent.on(this._container,"click",this._onMouseClick,this);for(var t=["dblclick","mousedown","mouseover","mouseout","mousemove","contextmenu"],e=0;e';var i=t.firstChild;return i.style.behavior="url(#default#VML)",i&&"object"==typeof i.adj}catch(n){return!1}}(),o.Path=o.Browser.svg||!o.Browser.vml?o.Path:o.Path.extend({statics:{VML:!0,CLIP_PADDING:.02},_createElement:function(){try{return e.namespaces.add("lvml","urn:schemas-microsoft-com:vml"),function(t){return e.createElement("')}}catch(t){return function(t){return e.createElement("<"+t+' xmlns="urn:schemas-microsoft.com:vml" class="lvml">')}}}(),_initPath:function(){var t=this._container=this._createElement("shape");o.DomUtil.addClass(t,"leaflet-vml-shape"+(this.options.className?" "+this.options.className:"")),this.options.clickable&&o.DomUtil.addClass(t,"leaflet-clickable"),t.coordsize="1 1",this._path=this._createElement("path"),t.appendChild(this._path),this._map._pathRoot.appendChild(t)},_initStyle:function(){this._updateStyle()},_updateStyle:function(){var t=this._stroke,e=this._fill,i=this.options,n=this._container;n.stroked=i.stroke,n.filled=i.fill,i.stroke?(t||(t=this._stroke=this._createElement("stroke"),t.endcap="round",n.appendChild(t)),t.weight=i.weight+"px",t.color=i.color,t.opacity=i.opacity,i.dashArray?t.dashStyle=o.Util.isArray(i.dashArray)?i.dashArray.join(" "):i.dashArray.replace(/( *, *)/g," "):t.dashStyle="",i.lineCap&&(t.endcap=i.lineCap.replace("butt","flat")),i.lineJoin&&(t.joinstyle=i.lineJoin)):t&&(n.removeChild(t),this._stroke=null),i.fill?(e||(e=this._fill=this._createElement("fill"),n.appendChild(e)),e.color=i.fillColor||i.color,e.opacity=i.fillOpacity):e&&(n.removeChild(e),this._fill=null)},_updatePath:function(){var t=this._container.style;t.display="none",this._path.v=this.getPathString()+" ",t.display=""}}),o.Map.include(o.Browser.svg||!o.Browser.vml?{}:{_initPathRoot:function(){if(!this._pathRoot){var t=this._pathRoot=e.createElement("div");t.className="leaflet-vml-container",this._panes.overlayPane.appendChild(t),this.on("moveend",this._updatePathViewport),this._updatePathViewport()}}}),o.Browser.canvas=function(){return!!e.createElement("canvas").getContext}(),o.Path=o.Path.SVG&&!t.L_PREFER_CANVAS||!o.Browser.canvas?o.Path:o.Path.extend({statics:{CANVAS:!0,SVG:!1},redraw:function(){return this._map&&(this.projectLatlngs(),this._requestUpdate()),this},setStyle:function(t){return o.setOptions(this,t),this._map&&(this._updateStyle(),this._requestUpdate()),this},onRemove:function(t){t.off("viewreset",this.projectLatlngs,this).off("moveend",this._updatePath,this),this.options.clickable&&(this._map.off("click",this._onClick,this),this._map.off("mousemove",this._onMouseMove,this)),this._requestUpdate(),this.fire("remove"),this._map=null},_requestUpdate:function(){this._map&&!o.Path._updateRequest&&(o.Path._updateRequest=o.Util.requestAnimFrame(this._fireMapMoveEnd,this._map))},_fireMapMoveEnd:function(){o.Path._updateRequest=null,this.fire("moveend")},_initElements:function(){this._map._initPathRoot(),this._ctx=this._map._canvasCtx},_updateStyle:function(){var t=this.options;t.stroke&&(this._ctx.lineWidth=t.weight,this._ctx.strokeStyle=t.color),t.fill&&(this._ctx.fillStyle=t.fillColor||t.color),t.lineCap&&(this._ctx.lineCap=t.lineCap),t.lineJoin&&(this._ctx.lineJoin=t.lineJoin)},_drawPath:function(){var t,e,i,n,s,a;for(this._ctx.beginPath(),t=0,i=this._parts.length;i>t;t++){for(e=0,n=this._parts[t].length;n>e;e++)s=this._parts[t][e],a=(0===e?"move":"line")+"To",this._ctx[a](s.x,s.y);this instanceof o.Polygon&&this._ctx.closePath()}},_checkIfEmpty:function(){return!this._parts.length},_updatePath:function(){if(!this._checkIfEmpty()){var t=this._ctx,e=this.options;this._drawPath(),t.save(),this._updateStyle(),e.fill&&(t.globalAlpha=e.fillOpacity,t.fill(e.fillRule||"evenodd")),e.stroke&&(t.globalAlpha=e.opacity,t.stroke()),t.restore()}},_initEvents:function(){this.options.clickable&&(this._map.on("mousemove",this._onMouseMove,this),this._map.on("click dblclick contextmenu",this._fireMouseEvent,this))},_fireMouseEvent:function(t){this._containsPoint(t.layerPoint)&&this.fire(t.type,t)},_onMouseMove:function(t){this._map&&!this._map._animatingZoom&&(this._containsPoint(t.layerPoint)?(this._ctx.canvas.style.cursor="pointer",this._mouseInside=!0,this.fire("mouseover",t)):this._mouseInside&&(this._ctx.canvas.style.cursor="",this._mouseInside=!1,this.fire("mouseout",t)))}}),o.Map.include(o.Path.SVG&&!t.L_PREFER_CANVAS||!o.Browser.canvas?{}:{_initPathRoot:function(){var t,i=this._pathRoot;i||(i=this._pathRoot=e.createElement("canvas"),i.style.position="absolute",t=this._canvasCtx=i.getContext("2d"),t.lineCap="round",t.lineJoin="round",this._panes.overlayPane.appendChild(i),this.options.zoomAnimation&&(this._pathRoot.className="leaflet-zoom-animated",this.on("zoomanim",this._animatePathZoom),this.on("zoomend",this._endPathZoom)),this.on("moveend",this._updateCanvasViewport),this._updateCanvasViewport())},_updateCanvasViewport:function(){if(!this._pathZooming){this._updatePathViewport();var t=this._pathViewport,e=t.min,i=t.max.subtract(e),n=this._pathRoot;o.DomUtil.setPosition(n,e),n.width=i.x,n.height=i.y,n.getContext("2d").translate(-e.x,-e.y)}}}),o.LineUtil={simplify:function(t,e){if(!e||!t.length)return t.slice();var i=e*e;return t=this._reducePoints(t,i),t=this._simplifyDP(t,i)},pointToSegmentDistance:function(t,e,i){return Math.sqrt(this._sqClosestPointOnSegment(t,e,i,!0))},closestPointOnSegment:function(t,e,i){return this._sqClosestPointOnSegment(t,e,i)},_simplifyDP:function(t,e){var n=t.length,o=typeof Uint8Array!=i+""?Uint8Array:Array,s=new o(n);s[0]=s[n-1]=1,this._simplifyDPStep(t,s,e,0,n-1);var a,r=[];for(a=0;n>a;a++)s[a]&&r.push(t[a]);return r},_simplifyDPStep:function(t,e,i,n,o){var s,a,r,h=0;for(a=n+1;o-1>=a;a++)r=this._sqClosestPointOnSegment(t[a],t[n],t[o],!0),r>h&&(s=a,h=r);h>i&&(e[s]=1,this._simplifyDPStep(t,e,i,n,s),this._simplifyDPStep(t,e,i,s,o))},_reducePoints:function(t,e){for(var i=[t[0]],n=1,o=0,s=t.length;s>n;n++)this._sqDist(t[n],t[o])>e&&(i.push(t[n]),o=n);return s-1>o&&i.push(t[s-1]),i},clipSegment:function(t,e,i,n){var o,s,a,r=n?this._lastCode:this._getBitCode(t,i),h=this._getBitCode(e,i);for(this._lastCode=h;;){if(!(r|h))return[t,e];if(r&h)return!1;o=r||h,s=this._getEdgeIntersection(t,e,o,i),a=this._getBitCode(s,i),o===r?(t=s,r=a):(e=s,h=a)}},_getEdgeIntersection:function(t,e,i,n){var s=e.x-t.x,a=e.y-t.y,r=n.min,h=n.max;return 8&i?new o.Point(t.x+s*(h.y-t.y)/a,h.y):4&i?new o.Point(t.x+s*(r.y-t.y)/a,r.y):2&i?new o.Point(h.x,t.y+a*(h.x-t.x)/s):1&i?new o.Point(r.x,t.y+a*(r.x-t.x)/s):void 0},_getBitCode:function(t,e){var i=0;return t.xe.max.x&&(i|=2),t.ye.max.y&&(i|=8),i},_sqDist:function(t,e){var i=e.x-t.x,n=e.y-t.y;return i*i+n*n},_sqClosestPointOnSegment:function(t,e,i,n){var s,a=e.x,r=e.y,h=i.x-a,l=i.y-r,u=h*h+l*l;return u>0&&(s=((t.x-a)*h+(t.y-r)*l)/u,s>1?(a=i.x,r=i.y):s>0&&(a+=h*s,r+=l*s)),h=t.x-a,l=t.y-r,n?h*h+l*l:new o.Point(a,r)}},o.Polyline=o.Path.extend({initialize:function(t,e){o.Path.prototype.initialize.call(this,e),this._latlngs=this._convertLatLngs(t)},options:{smoothFactor:1,noClip:!1},projectLatlngs:function(){this._originalPoints=[];for(var t=0,e=this._latlngs.length;e>t;t++)this._originalPoints[t]=this._map.latLngToLayerPoint(this._latlngs[t])},getPathString:function(){for(var t=0,e=this._parts.length,i="";e>t;t++)i+=this._getPathPartStr(this._parts[t]);return i},getLatLngs:function(){return this._latlngs},setLatLngs:function(t){return this._latlngs=this._convertLatLngs(t),this.redraw()},addLatLng:function(t){return this._latlngs.push(o.latLng(t)),this.redraw()},spliceLatLngs:function(){var t=[].splice.apply(this._latlngs,arguments);return this._convertLatLngs(this._latlngs,!0),this.redraw(),t},closestLayerPoint:function(t){for(var e,i,n=1/0,s=this._parts,a=null,r=0,h=s.length;h>r;r++)for(var l=s[r],u=1,c=l.length;c>u;u++){e=l[u-1],i=l[u];var d=o.LineUtil._sqClosestPointOnSegment(t,e,i,!0);n>d&&(n=d,a=o.LineUtil._sqClosestPointOnSegment(t,e,i))}return a&&(a.distance=Math.sqrt(n)),a},getBounds:function(){return new o.LatLngBounds(this.getLatLngs())},_convertLatLngs:function(t,e){var i,n,s=e?t:[];for(i=0,n=t.length;n>i;i++){if(o.Util.isArray(t[i])&&"number"!=typeof t[i][0])return;s[i]=o.latLng(t[i])}return s},_initEvents:function(){o.Path.prototype._initEvents.call(this)},_getPathPartStr:function(t){for(var e,i=o.Path.VML,n=0,s=t.length,a="";s>n;n++)e=t[n],i&&e._round(),a+=(n?"L":"M")+e.x+" "+e.y;return a},_clipPoints:function(){var t,e,i,n=this._originalPoints,s=n.length;if(this.options.noClip)return void(this._parts=[n]);this._parts=[];var a=this._parts,r=this._map._pathViewport,h=o.LineUtil;for(t=0,e=0;s-1>t;t++)i=h.clipSegment(n[t],n[t+1],r,t),i&&(a[e]=a[e]||[],a[e].push(i[0]),(i[1]!==n[t+1]||t===s-2)&&(a[e].push(i[1]),e++))},_simplifyPoints:function(){for(var t=this._parts,e=o.LineUtil,i=0,n=t.length;n>i;i++)t[i]=e.simplify(t[i],this.options.smoothFactor)},_updatePath:function(){this._map&&(this._clipPoints(),this._simplifyPoints(),o.Path.prototype._updatePath.call(this))}}),o.polyline=function(t,e){return new o.Polyline(t,e)},o.PolyUtil={},o.PolyUtil.clipPolygon=function(t,e){var i,n,s,a,r,h,l,u,c,d=[1,4,2,8],p=o.LineUtil;for(n=0,l=t.length;l>n;n++)t[n]._code=p._getBitCode(t[n],e);for(a=0;4>a;a++){for(u=d[a],i=[],n=0,l=t.length,s=l-1;l>n;s=n++)r=t[n],h=t[s],r._code&u?h._code&u||(c=p._getEdgeIntersection(h,r,u,e),c._code=p._getBitCode(c,e),i.push(c)):(h._code&u&&(c=p._getEdgeIntersection(h,r,u,e),c._code=p._getBitCode(c,e),i.push(c)),i.push(r));t=i}return t},o.Polygon=o.Polyline.extend({options:{fill:!0},initialize:function(t,e){o.Polyline.prototype.initialize.call(this,t,e),this._initWithHoles(t)},_initWithHoles:function(t){var e,i,n;if(t&&o.Util.isArray(t[0])&&"number"!=typeof t[0][0])for(this._latlngs=this._convertLatLngs(t[0]),this._holes=t.slice(1),e=0,i=this._holes.length;i>e;e++)n=this._holes[e]=this._convertLatLngs(this._holes[e]),n[0].equals(n[n.length-1])&&n.pop();t=this._latlngs,t.length>=2&&t[0].equals(t[t.length-1])&&t.pop()},projectLatlngs:function(){if(o.Polyline.prototype.projectLatlngs.call(this),this._holePoints=[],this._holes){var t,e,i,n;for(t=0,i=this._holes.length;i>t;t++)for(this._holePoints[t]=[],e=0,n=this._holes[t].length;n>e;e++)this._holePoints[t][e]=this._map.latLngToLayerPoint(this._holes[t][e])}},setLatLngs:function(t){return t&&o.Util.isArray(t[0])&&"number"!=typeof t[0][0]?(this._initWithHoles(t),this.redraw()):o.Polyline.prototype.setLatLngs.call(this,t)},_clipPoints:function(){var t=this._originalPoints,e=[];if(this._parts=[t].concat(this._holePoints),!this.options.noClip){for(var i=0,n=this._parts.length;n>i;i++){var s=o.PolyUtil.clipPolygon(this._parts[i],this._map._pathViewport);s.length&&e.push(s)}this._parts=e}},_getPathPartStr:function(t){var e=o.Polyline.prototype._getPathPartStr.call(this,t);return e+(o.Browser.svg?"z":"x")}}),o.polygon=function(t,e){return new o.Polygon(t,e)},function(){function t(t){return o.FeatureGroup.extend({initialize:function(t,e){this._layers={},this._options=e,this.setLatLngs(t)},setLatLngs:function(e){var i=0,n=e.length;for(this.eachLayer(function(t){n>i?t.setLatLngs(e[i++]):this.removeLayer(t)},this);n>i;)this.addLayer(new t(e[i++],this._options));return this},getLatLngs:function(){var t=[];return this.eachLayer(function(e){t.push(e.getLatLngs())}),t}})}o.MultiPolyline=t(o.Polyline),o.MultiPolygon=t(o.Polygon),o.multiPolyline=function(t,e){return new o.MultiPolyline(t,e)},o.multiPolygon=function(t,e){return new o.MultiPolygon(t,e)}}(),o.Rectangle=o.Polygon.extend({initialize:function(t,e){o.Polygon.prototype.initialize.call(this,this._boundsToLatLngs(t),e)},setBounds:function(t){this.setLatLngs(this._boundsToLatLngs(t))},_boundsToLatLngs:function(t){return t=o.latLngBounds(t),[t.getSouthWest(),t.getNorthWest(),t.getNorthEast(),t.getSouthEast()]}}),o.rectangle=function(t,e){return new o.Rectangle(t,e)},o.Circle=o.Path.extend({initialize:function(t,e,i){o.Path.prototype.initialize.call(this,i),this._latlng=o.latLng(t),this._mRadius=e},options:{fill:!0},setLatLng:function(t){return this._latlng=o.latLng(t),this.redraw()},setRadius:function(t){return this._mRadius=t,this.redraw()},projectLatlngs:function(){var t=this._getLngRadius(),e=this._latlng,i=this._map.latLngToLayerPoint([e.lat,e.lng-t]);this._point=this._map.latLngToLayerPoint(e),this._radius=Math.max(this._point.x-i.x,1)},getBounds:function(){var t=this._getLngRadius(),e=this._mRadius/40075017*360,i=this._latlng;return new o.LatLngBounds([i.lat-e,i.lng-t],[i.lat+e,i.lng+t])},getLatLng:function(){return this._latlng},getPathString:function(){var t=this._point,e=this._radius;return this._checkIfEmpty()?"":o.Browser.svg?"M"+t.x+","+(t.y-e)+"A"+e+","+e+",0,1,1,"+(t.x-.1)+","+(t.y-e)+" z":(t._round(),e=Math.round(e),"AL "+t.x+","+t.y+" "+e+","+e+" 0,23592600")},getRadius:function(){return this._mRadius},_getLatRadius:function(){return this._mRadius/40075017*360},_getLngRadius:function(){return this._getLatRadius()/Math.cos(o.LatLng.DEG_TO_RAD*this._latlng.lat)},_checkIfEmpty:function(){if(!this._map)return!1;var t=this._map._pathViewport,e=this._radius,i=this._point;return i.x-e>t.max.x||i.y-e>t.max.y||i.x+ei;i++)for(l=this._parts[i],n=0,r=l.length,s=r-1;r>n;s=n++)if((e||0!==n)&&(h=o.LineUtil.pointToSegmentDistance(t,l[s],l[n]),u>=h))return!0;return!1}}:{}),o.Polygon.include(o.Path.CANVAS?{_containsPoint:function(t){var e,i,n,s,a,r,h,l,u=!1;if(o.Polyline.prototype._containsPoint.call(this,t,!0))return!0;for(s=0,h=this._parts.length;h>s;s++)for(e=this._parts[s],a=0,l=e.length,r=l-1;l>a;r=a++)i=e[a],n=e[r],i.y>t.y!=n.y>t.y&&t.x<(n.x-i.x)*(t.y-i.y)/(n.y-i.y)+i.x&&(u=!u);return u}}:{}),o.Circle.include(o.Path.CANVAS?{_drawPath:function(){var t=this._point;this._ctx.beginPath(),this._ctx.arc(t.x,t.y,this._radius,0,2*Math.PI,!1)},_containsPoint:function(t){var e=this._point,i=this.options.stroke?this.options.weight/2:0;return t.distanceTo(e)<=this._radius+i}}:{}),o.CircleMarker.include(o.Path.CANVAS?{_updateStyle:function(){o.Path.prototype._updateStyle.call(this)}}:{}),o.GeoJSON=o.FeatureGroup.extend({initialize:function(t,e){o.setOptions(this,e),this._layers={},t&&this.addData(t)},addData:function(t){var e,i,n,s=o.Util.isArray(t)?t:t.features;if(s){for(e=0,i=s.length;i>e;e++)n=s[e],(n.geometries||n.geometry||n.features||n.coordinates)&&this.addData(s[e]);return this}var a=this.options;if(!a.filter||a.filter(t)){var r=o.GeoJSON.geometryToLayer(t,a.pointToLayer,a.coordsToLatLng,a);return r.feature=o.GeoJSON.asFeature(t),r.defaultOptions=r.options,this.resetStyle(r),a.onEachFeature&&a.onEachFeature(t,r),this.addLayer(r)}},resetStyle:function(t){var e=this.options.style;e&&(o.Util.extend(t.options,t.defaultOptions),this._setLayerStyle(t,e))},setStyle:function(t){this.eachLayer(function(e){this._setLayerStyle(e,t)},this)},_setLayerStyle:function(t,e){"function"==typeof e&&(e=e(t.feature)),t.setStyle&&t.setStyle(e)}}),o.extend(o.GeoJSON,{geometryToLayer:function(t,e,i,n){var s,a,r,h,l="Feature"===t.type?t.geometry:t,u=l.coordinates,c=[];switch(i=i||this.coordsToLatLng,l.type){case"Point":return s=i(u),e?e(t,s):new o.Marker(s);case"MultiPoint":for(r=0,h=u.length;h>r;r++)s=i(u[r]),c.push(e?e(t,s):new o.Marker(s));return new o.FeatureGroup(c);case"LineString":return a=this.coordsToLatLngs(u,0,i),new o.Polyline(a,n);case"Polygon":if(2===u.length&&!u[1].length)throw new Error("Invalid GeoJSON object.");return a=this.coordsToLatLngs(u,1,i),new o.Polygon(a,n);case"MultiLineString":return a=this.coordsToLatLngs(u,1,i),new o.MultiPolyline(a,n);case"MultiPolygon":return a=this.coordsToLatLngs(u,2,i),new o.MultiPolygon(a,n);case"GeometryCollection":for(r=0,h=l.geometries.length;h>r;r++)c.push(this.geometryToLayer({geometry:l.geometries[r],type:"Feature",properties:t.properties},e,i,n));return new o.FeatureGroup(c);default:throw new Error("Invalid GeoJSON object.")}},coordsToLatLng:function(t){return new o.LatLng(t[1],t[0],t[2])},coordsToLatLngs:function(t,e,i){var n,o,s,a=[];for(o=0,s=t.length;s>o;o++)n=e?this.coordsToLatLngs(t[o],e-1,i):(i||this.coordsToLatLng)(t[o]),a.push(n);return a},latLngToCoords:function(t){var e=[t.lng,t.lat];return t.alt!==i&&e.push(t.alt),e},latLngsToCoords:function(t){for(var e=[],i=0,n=t.length;n>i;i++)e.push(o.GeoJSON.latLngToCoords(t[i]));return e},getFeature:function(t,e){return t.feature?o.extend({},t.feature,{geometry:e}):o.GeoJSON.asFeature(e)},asFeature:function(t){return"Feature"===t.type?t:{type:"Feature",properties:{},geometry:t}}});var a={toGeoJSON:function(){return o.GeoJSON.getFeature(this,{type:"Point",coordinates:o.GeoJSON.latLngToCoords(this.getLatLng())})}};o.Marker.include(a),o.Circle.include(a),o.CircleMarker.include(a),o.Polyline.include({toGeoJSON:function(){return o.GeoJSON.getFeature(this,{type:"LineString",coordinates:o.GeoJSON.latLngsToCoords(this.getLatLngs())})}}),o.Polygon.include({toGeoJSON:function(){var t,e,i,n=[o.GeoJSON.latLngsToCoords(this.getLatLngs())];if(n[0].push(n[0][0]),this._holes)for(t=0,e=this._holes.length;e>t;t++)i=o.GeoJSON.latLngsToCoords(this._holes[t]),i.push(i[0]),n.push(i);return o.GeoJSON.getFeature(this,{type:"Polygon",coordinates:n})}}),function(){function t(t){return function(){var e=[];return this.eachLayer(function(t){e.push(t.toGeoJSON().geometry.coordinates)}),o.GeoJSON.getFeature(this,{type:t,coordinates:e})}}o.MultiPolyline.include({toGeoJSON:t("MultiLineString")}),o.MultiPolygon.include({toGeoJSON:t("MultiPolygon")}),o.LayerGroup.include({toGeoJSON:function(){var e,i=this.feature&&this.feature.geometry,n=[];if(i&&"MultiPoint"===i.type)return t("MultiPoint").call(this);var s=i&&"GeometryCollection"===i.type;return this.eachLayer(function(t){t.toGeoJSON&&(e=t.toGeoJSON(),n.push(s?e.geometry:o.GeoJSON.asFeature(e)))}),s?o.GeoJSON.getFeature(this,{geometries:n,type:"GeometryCollection"}):{type:"FeatureCollection",features:n}}})}(),o.geoJson=function(t,e){return new o.GeoJSON(t,e)},o.DomEvent={addListener:function(t,e,i,n){var s,a,r,h=o.stamp(i),l="_leaflet_"+e+h;return t[l]?this:(s=function(e){return i.call(n||t,e||o.DomEvent._getEvent())},o.Browser.pointer&&0===e.indexOf("touch")?this.addPointerListener(t,e,s,h):(o.Browser.touch&&"dblclick"===e&&this.addDoubleTapListener&&this.addDoubleTapListener(t,s,h),"addEventListener"in t?"mousewheel"===e?(t.addEventListener("DOMMouseScroll",s,!1),t.addEventListener(e,s,!1)):"mouseenter"===e||"mouseleave"===e?(a=s,r="mouseenter"===e?"mouseover":"mouseout",s=function(e){return o.DomEvent._checkMouse(t,e)?a(e):void 0},t.addEventListener(r,s,!1)):"click"===e&&o.Browser.android?(a=s,s=function(t){return o.DomEvent._filterClick(t,a)},t.addEventListener(e,s,!1)):t.addEventListener(e,s,!1):"attachEvent"in t&&t.attachEvent("on"+e,s),t[l]=s,this))},removeListener:function(t,e,i){var n=o.stamp(i),s="_leaflet_"+e+n,a=t[s];return a?(o.Browser.pointer&&0===e.indexOf("touch")?this.removePointerListener(t,e,n):o.Browser.touch&&"dblclick"===e&&this.removeDoubleTapListener?this.removeDoubleTapListener(t,n):"removeEventListener"in t?"mousewheel"===e?(t.removeEventListener("DOMMouseScroll",a,!1),t.removeEventListener(e,a,!1)):"mouseenter"===e||"mouseleave"===e?t.removeEventListener("mouseenter"===e?"mouseover":"mouseout",a,!1):t.removeEventListener(e,a,!1):"detachEvent"in t&&t.detachEvent("on"+e,a),t[s]=null,this):this},stopPropagation:function(t){return t.stopPropagation?t.stopPropagation():t.cancelBubble=!0,o.DomEvent._skipped(t),this},disableScrollPropagation:function(t){var e=o.DomEvent.stopPropagation;return o.DomEvent.on(t,"mousewheel",e).on(t,"MozMousePixelScroll",e)},disableClickPropagation:function(t){for(var e=o.DomEvent.stopPropagation,i=o.Draggable.START.length-1;i>=0;i--)o.DomEvent.on(t,o.Draggable.START[i],e);return o.DomEvent.on(t,"click",o.DomEvent._fakeStop).on(t,"dblclick",e)},preventDefault:function(t){return t.preventDefault?t.preventDefault():t.returnValue=!1,this},stop:function(t){return o.DomEvent.preventDefault(t).stopPropagation(t)},getMousePosition:function(t,e){if(!e)return new o.Point(t.clientX,t.clientY);var i=e.getBoundingClientRect();return new o.Point(t.clientX-i.left-e.clientLeft,t.clientY-i.top-e.clientTop)},getWheelDelta:function(t){var e=0;return t.wheelDelta&&(e=t.wheelDelta/120),t.detail&&(e=-t.detail/3),e},_skipEvents:{},_fakeStop:function(t){o.DomEvent._skipEvents[t.type]=!0},_skipped:function(t){var e=this._skipEvents[t.type];return this._skipEvents[t.type]=!1,e},_checkMouse:function(t,e){var i=e.relatedTarget;if(!i)return!0;try{for(;i&&i!==t;)i=i.parentNode}catch(n){return!1}return i!==t},_getEvent:function(){var e=t.event;if(!e)for(var i=arguments.callee.caller;i&&(e=i.arguments[0],!e||t.Event!==e.constructor);)i=i.caller;return e},_filterClick:function(t,e){var i=t.timeStamp||t.originalEvent.timeStamp,n=o.DomEvent._lastClick&&i-o.DomEvent._lastClick;return n&&n>100&&500>n||t.target._simulatedClick&&!t._simulated?void o.DomEvent.stop(t):(o.DomEvent._lastClick=i,e(t))}},o.DomEvent.on=o.DomEvent.addListener,o.DomEvent.off=o.DomEvent.removeListener,o.Draggable=o.Class.extend({includes:o.Mixin.Events,statics:{START:o.Browser.touch?["touchstart","mousedown"]:["mousedown"],END:{mousedown:"mouseup",touchstart:"touchend",pointerdown:"touchend",MSPointerDown:"touchend"},MOVE:{mousedown:"mousemove",touchstart:"touchmove",pointerdown:"touchmove",MSPointerDown:"touchmove"}},initialize:function(t,e){this._element=t,this._dragStartTarget=e||t},enable:function(){if(!this._enabled){for(var t=o.Draggable.START.length-1;t>=0;t--)o.DomEvent.on(this._dragStartTarget,o.Draggable.START[t],this._onDown,this);this._enabled=!0}},disable:function(){if(this._enabled){for(var t=o.Draggable.START.length-1;t>=0;t--)o.DomEvent.off(this._dragStartTarget,o.Draggable.START[t],this._onDown,this);this._enabled=!1,this._moved=!1}},_onDown:function(t){if(this._moved=!1,!t.shiftKey&&(1===t.which||1===t.button||t.touches)&&(o.DomEvent.stopPropagation(t),!o.Draggable._disabled&&(o.DomUtil.disableImageDrag(),o.DomUtil.disableTextSelection(),!this._moving))){var i=t.touches?t.touches[0]:t;this._startPoint=new o.Point(i.clientX,i.clientY),this._startPos=this._newPos=o.DomUtil.getPosition(this._element),o.DomEvent.on(e,o.Draggable.MOVE[t.type],this._onMove,this).on(e,o.Draggable.END[t.type],this._onUp,this)}},_onMove:function(t){if(t.touches&&t.touches.length>1)return void(this._moved=!0);var i=t.touches&&1===t.touches.length?t.touches[0]:t,n=new o.Point(i.clientX,i.clientY),s=n.subtract(this._startPoint);(s.x||s.y)&&(o.Browser.touch&&Math.abs(s.x)+Math.abs(s.y)<3||(o.DomEvent.preventDefault(t),this._moved||(this.fire("dragstart"),this._moved=!0,this._startPos=o.DomUtil.getPosition(this._element).subtract(s),o.DomUtil.addClass(e.body,"leaflet-dragging"),this._lastTarget=t.target||t.srcElement,o.DomUtil.addClass(this._lastTarget,"leaflet-drag-target")),this._newPos=this._startPos.add(s),this._moving=!0,o.Util.cancelAnimFrame(this._animRequest),this._animRequest=o.Util.requestAnimFrame(this._updatePosition,this,!0,this._dragStartTarget)))},_updatePosition:function(){this.fire("predrag"),o.DomUtil.setPosition(this._element,this._newPos),this.fire("drag")},_onUp:function(){o.DomUtil.removeClass(e.body,"leaflet-dragging"),this._lastTarget&&(o.DomUtil.removeClass(this._lastTarget,"leaflet-drag-target"),this._lastTarget=null);for(var t in o.Draggable.MOVE)o.DomEvent.off(e,o.Draggable.MOVE[t],this._onMove).off(e,o.Draggable.END[t],this._onUp);o.DomUtil.enableImageDrag(),o.DomUtil.enableTextSelection(),this._moved&&this._moving&&(o.Util.cancelAnimFrame(this._animRequest),this.fire("dragend",{distance:this._newPos.distanceTo(this._startPos)})),this._moving=!1}}),o.Handler=o.Class.extend({initialize:function(t){this._map=t},enable:function(){this._enabled||(this._enabled=!0,this.addHooks())},disable:function(){this._enabled&&(this._enabled=!1,this.removeHooks())},enabled:function(){return!!this._enabled}}),o.Map.mergeOptions({dragging:!0,inertia:!o.Browser.android23,inertiaDeceleration:3400,inertiaMaxSpeed:1/0,inertiaThreshold:o.Browser.touch?32:18,easeLinearity:.25,worldCopyJump:!1}),o.Map.Drag=o.Handler.extend({addHooks:function(){if(!this._draggable){var t=this._map;this._draggable=new o.Draggable(t._mapPane,t._container),this._draggable.on({dragstart:this._onDragStart,drag:this._onDrag,dragend:this._onDragEnd},this),t.options.worldCopyJump&&(this._draggable.on("predrag",this._onPreDrag,this),t.on("viewreset",this._onViewReset,this),t.whenReady(this._onViewReset,this))}this._draggable.enable()},removeHooks:function(){this._draggable.disable()},moved:function(){return this._draggable&&this._draggable._moved},_onDragStart:function(){var t=this._map;t._panAnim&&t._panAnim.stop(),t.fire("movestart").fire("dragstart"),t.options.inertia&&(this._positions=[],this._times=[])},_onDrag:function(){if(this._map.options.inertia){var t=this._lastTime=+new Date,e=this._lastPos=this._draggable._newPos;this._positions.push(e),this._times.push(t),t-this._times[0]>200&&(this._positions.shift(),this._times.shift())}this._map.fire("move").fire("drag")},_onViewReset:function(){var t=this._map.getSize()._divideBy(2),e=this._map.latLngToLayerPoint([0,0]);this._initialWorldOffset=e.subtract(t).x,this._worldWidth=this._map.project([0,180]).x},_onPreDrag:function(){var t=this._worldWidth,e=Math.round(t/2),i=this._initialWorldOffset,n=this._draggable._newPos.x,o=(n-e+i)%t+e-i,s=(n+e+i)%t-e-i,a=Math.abs(o+i)i.inertiaThreshold||!this._positions[0];if(e.fire("dragend",t),s)e.fire("moveend");else{var a=this._lastPos.subtract(this._positions[0]),r=(this._lastTime+n-this._times[0])/1e3,h=i.easeLinearity,l=a.multiplyBy(h/r),u=l.distanceTo([0,0]),c=Math.min(i.inertiaMaxSpeed,u),d=l.multiplyBy(c/u),p=c/(i.inertiaDeceleration*h),_=d.multiplyBy(-p/2).round();_.x&&_.y?(_=e._limitOffset(_,e.options.maxBounds),o.Util.requestAnimFrame(function(){e.panBy(_,{duration:p,easeLinearity:h,noMoveStart:!0})})):e.fire("moveend")}}}),o.Map.addInitHook("addHandler","dragging",o.Map.Drag),o.Map.mergeOptions({doubleClickZoom:!0}),o.Map.DoubleClickZoom=o.Handler.extend({addHooks:function(){this._map.on("dblclick",this._onDoubleClick,this)},removeHooks:function(){this._map.off("dblclick",this._onDoubleClick,this)},_onDoubleClick:function(t){var e=this._map,i=e.getZoom()+(t.originalEvent.shiftKey?-1:1);"center"===e.options.doubleClickZoom?e.setZoom(i):e.setZoomAround(t.containerPoint,i)}}),o.Map.addInitHook("addHandler","doubleClickZoom",o.Map.DoubleClickZoom),o.Map.mergeOptions({scrollWheelZoom:!0}),o.Map.ScrollWheelZoom=o.Handler.extend({addHooks:function(){o.DomEvent.on(this._map._container,"mousewheel",this._onWheelScroll,this),o.DomEvent.on(this._map._container,"MozMousePixelScroll",o.DomEvent.preventDefault),this._delta=0},removeHooks:function(){o.DomEvent.off(this._map._container,"mousewheel",this._onWheelScroll),o.DomEvent.off(this._map._container,"MozMousePixelScroll",o.DomEvent.preventDefault)},_onWheelScroll:function(t){var e=o.DomEvent.getWheelDelta(t);this._delta+=e,this._lastMousePos=this._map.mouseEventToContainerPoint(t),this._startTime||(this._startTime=+new Date);var i=Math.max(40-(+new Date-this._startTime),0);clearTimeout(this._timer),this._timer=setTimeout(o.bind(this._performZoom,this),i),o.DomEvent.preventDefault(t),o.DomEvent.stopPropagation(t)},_performZoom:function(){var t=this._map,e=this._delta,i=t.getZoom();e=e>0?Math.ceil(e):Math.floor(e),e=Math.max(Math.min(e,4),-4),e=t._limitZoom(i+e)-i,this._delta=0,this._startTime=null,e&&("center"===t.options.scrollWheelZoom?t.setZoom(i+e):t.setZoomAround(this._lastMousePos,i+e))}}),o.Map.addInitHook("addHandler","scrollWheelZoom",o.Map.ScrollWheelZoom),o.extend(o.DomEvent,{_touchstart:o.Browser.msPointer?"MSPointerDown":o.Browser.pointer?"pointerdown":"touchstart",_touchend:o.Browser.msPointer?"MSPointerUp":o.Browser.pointer?"pointerup":"touchend",addDoubleTapListener:function(t,i,n){function s(t){var e;if(o.Browser.pointer?(_.push(t.pointerId),e=_.length):e=t.touches.length,!(e>1)){var i=Date.now(),n=i-(r||i);h=t.touches?t.touches[0]:t,l=n>0&&u>=n,r=i}}function a(t){if(o.Browser.pointer){var e=_.indexOf(t.pointerId);if(-1===e)return;_.splice(e,1)}if(l){if(o.Browser.pointer){var n,s={};for(var a in h)n=h[a],"function"==typeof n?s[a]=n.bind(h):s[a]=n;h=s}h.type="dblclick",i(h),r=null}}var r,h,l=!1,u=250,c="_leaflet_",d=this._touchstart,p=this._touchend,_=[];t[c+d+n]=s,t[c+p+n]=a;var m=o.Browser.pointer?e.documentElement:t;return t.addEventListener(d,s,!1),m.addEventListener(p,a,!1),o.Browser.pointer&&m.addEventListener(o.DomEvent.POINTER_CANCEL,a,!1),this},removeDoubleTapListener:function(t,i){var n="_leaflet_";return t.removeEventListener(this._touchstart,t[n+this._touchstart+i],!1),(o.Browser.pointer?e.documentElement:t).removeEventListener(this._touchend,t[n+this._touchend+i],!1),o.Browser.pointer&&e.documentElement.removeEventListener(o.DomEvent.POINTER_CANCEL,t[n+this._touchend+i],!1),this}}),o.extend(o.DomEvent,{POINTER_DOWN:o.Browser.msPointer?"MSPointerDown":"pointerdown",POINTER_MOVE:o.Browser.msPointer?"MSPointerMove":"pointermove",POINTER_UP:o.Browser.msPointer?"MSPointerUp":"pointerup",POINTER_CANCEL:o.Browser.msPointer?"MSPointerCancel":"pointercancel",_pointers:[],_pointerDocumentListener:!1,addPointerListener:function(t,e,i,n){switch(e){case"touchstart":return this.addPointerListenerStart(t,e,i,n); -case"touchend":return this.addPointerListenerEnd(t,e,i,n);case"touchmove":return this.addPointerListenerMove(t,e,i,n);default:throw"Unknown touch event type"}},addPointerListenerStart:function(t,i,n,s){var a="_leaflet_",r=this._pointers,h=function(t){"mouse"!==t.pointerType&&t.pointerType!==t.MSPOINTER_TYPE_MOUSE&&o.DomEvent.preventDefault(t);for(var e=!1,i=0;i1))&&(this._moved||(o.DomUtil.addClass(e._mapPane,"leaflet-touching"),e.fire("movestart").fire("zoomstart"),this._moved=!0),o.Util.cancelAnimFrame(this._animRequest),this._animRequest=o.Util.requestAnimFrame(this._updateOnMove,this,!0,this._map._container),o.DomEvent.preventDefault(t))}},_updateOnMove:function(){var t=this._map,e=this._getScaleOrigin(),i=t.layerPointToLatLng(e),n=t.getScaleZoom(this._scale);t._animateZoom(i,n,this._startCenter,this._scale,this._delta,!1,!0)},_onTouchEnd:function(){if(!this._moved||!this._zooming)return void(this._zooming=!1);var t=this._map;this._zooming=!1,o.DomUtil.removeClass(t._mapPane,"leaflet-touching"),o.Util.cancelAnimFrame(this._animRequest),o.DomEvent.off(e,"touchmove",this._onTouchMove).off(e,"touchend",this._onTouchEnd);var i=this._getScaleOrigin(),n=t.layerPointToLatLng(i),s=t.getZoom(),a=t.getScaleZoom(this._scale)-s,r=a>0?Math.ceil(a):Math.floor(a),h=t._limitZoom(s+r),l=t.getZoomScale(h)/this._scale;t._animateZoom(n,h,i,l)},_getScaleOrigin:function(){var t=this._centerOffset.subtract(this._delta).divideBy(this._scale);return this._startCenter.add(t)}}),o.Map.addInitHook("addHandler","touchZoom",o.Map.TouchZoom),o.Map.mergeOptions({tap:!0,tapTolerance:15}),o.Map.Tap=o.Handler.extend({addHooks:function(){o.DomEvent.on(this._map._container,"touchstart",this._onDown,this)},removeHooks:function(){o.DomEvent.off(this._map._container,"touchstart",this._onDown,this)},_onDown:function(t){if(t.touches){if(o.DomEvent.preventDefault(t),this._fireClick=!0,t.touches.length>1)return this._fireClick=!1,void clearTimeout(this._holdTimeout);var i=t.touches[0],n=i.target;this._startPos=this._newPos=new o.Point(i.clientX,i.clientY),n.tagName&&"a"===n.tagName.toLowerCase()&&o.DomUtil.addClass(n,"leaflet-active"),this._holdTimeout=setTimeout(o.bind(function(){this._isTapValid()&&(this._fireClick=!1,this._onUp(),this._simulateEvent("contextmenu",i))},this),1e3),o.DomEvent.on(e,"touchmove",this._onMove,this).on(e,"touchend",this._onUp,this)}},_onUp:function(t){if(clearTimeout(this._holdTimeout),o.DomEvent.off(e,"touchmove",this._onMove,this).off(e,"touchend",this._onUp,this),this._fireClick&&t&&t.changedTouches){var i=t.changedTouches[0],n=i.target;n&&n.tagName&&"a"===n.tagName.toLowerCase()&&o.DomUtil.removeClass(n,"leaflet-active"),this._isTapValid()&&this._simulateEvent("click",i)}},_isTapValid:function(){return this._newPos.distanceTo(this._startPos)<=this._map.options.tapTolerance},_onMove:function(t){var e=t.touches[0];this._newPos=new o.Point(e.clientX,e.clientY)},_simulateEvent:function(i,n){var o=e.createEvent("MouseEvents");o._simulated=!0,n.target._simulatedClick=!0,o.initMouseEvent(i,!0,!0,t,1,n.screenX,n.screenY,n.clientX,n.clientY,!1,!1,!1,!1,0,null),n.target.dispatchEvent(o)}}),o.Browser.touch&&!o.Browser.pointer&&o.Map.addInitHook("addHandler","tap",o.Map.Tap),o.Map.mergeOptions({boxZoom:!0}),o.Map.BoxZoom=o.Handler.extend({initialize:function(t){this._map=t,this._container=t._container,this._pane=t._panes.overlayPane,this._moved=!1},addHooks:function(){o.DomEvent.on(this._container,"mousedown",this._onMouseDown,this)},removeHooks:function(){o.DomEvent.off(this._container,"mousedown",this._onMouseDown),this._moved=!1},moved:function(){return this._moved},_onMouseDown:function(t){return this._moved=!1,!t.shiftKey||1!==t.which&&1!==t.button?!1:(o.DomUtil.disableTextSelection(),o.DomUtil.disableImageDrag(),this._startLayerPoint=this._map.mouseEventToLayerPoint(t),void o.DomEvent.on(e,"mousemove",this._onMouseMove,this).on(e,"mouseup",this._onMouseUp,this).on(e,"keydown",this._onKeyDown,this))},_onMouseMove:function(t){this._moved||(this._box=o.DomUtil.create("div","leaflet-zoom-box",this._pane),o.DomUtil.setPosition(this._box,this._startLayerPoint),this._container.style.cursor="crosshair",this._map.fire("boxzoomstart"));var e=this._startLayerPoint,i=this._box,n=this._map.mouseEventToLayerPoint(t),s=n.subtract(e),a=new o.Point(Math.min(n.x,e.x),Math.min(n.y,e.y));o.DomUtil.setPosition(i,a),this._moved=!0,i.style.width=Math.max(0,Math.abs(s.x)-4)+"px",i.style.height=Math.max(0,Math.abs(s.y)-4)+"px"},_finish:function(){this._moved&&(this._pane.removeChild(this._box),this._container.style.cursor=""),o.DomUtil.enableTextSelection(),o.DomUtil.enableImageDrag(),o.DomEvent.off(e,"mousemove",this._onMouseMove).off(e,"mouseup",this._onMouseUp).off(e,"keydown",this._onKeyDown)},_onMouseUp:function(t){this._finish();var e=this._map,i=e.mouseEventToLayerPoint(t);if(!this._startLayerPoint.equals(i)){var n=new o.LatLngBounds(e.layerPointToLatLng(this._startLayerPoint),e.layerPointToLatLng(i));e.fitBounds(n),e.fire("boxzoomend",{boxZoomBounds:n})}},_onKeyDown:function(t){27===t.keyCode&&this._finish()}}),o.Map.addInitHook("addHandler","boxZoom",o.Map.BoxZoom),o.Map.mergeOptions({keyboard:!0,keyboardPanOffset:80,keyboardZoomOffset:1}),o.Map.Keyboard=o.Handler.extend({keyCodes:{left:[37],right:[39],down:[40],up:[38],zoomIn:[187,107,61,171],zoomOut:[189,109,173]},initialize:function(t){this._map=t,this._setPanOffset(t.options.keyboardPanOffset),this._setZoomOffset(t.options.keyboardZoomOffset)},addHooks:function(){var t=this._map._container;-1===t.tabIndex&&(t.tabIndex="0"),o.DomEvent.on(t,"focus",this._onFocus,this).on(t,"blur",this._onBlur,this).on(t,"mousedown",this._onMouseDown,this),this._map.on("focus",this._addHooks,this).on("blur",this._removeHooks,this)},removeHooks:function(){this._removeHooks();var t=this._map._container;o.DomEvent.off(t,"focus",this._onFocus,this).off(t,"blur",this._onBlur,this).off(t,"mousedown",this._onMouseDown,this),this._map.off("focus",this._addHooks,this).off("blur",this._removeHooks,this)},_onMouseDown:function(){if(!this._focused){var i=e.body,n=e.documentElement,o=i.scrollTop||n.scrollTop,s=i.scrollLeft||n.scrollLeft;this._map._container.focus(),t.scrollTo(s,o)}},_onFocus:function(){this._focused=!0,this._map.fire("focus")},_onBlur:function(){this._focused=!1,this._map.fire("blur")},_setPanOffset:function(t){var e,i,n=this._panKeys={},o=this.keyCodes;for(e=0,i=o.left.length;i>e;e++)n[o.left[e]]=[-1*t,0];for(e=0,i=o.right.length;i>e;e++)n[o.right[e]]=[t,0];for(e=0,i=o.down.length;i>e;e++)n[o.down[e]]=[0,t];for(e=0,i=o.up.length;i>e;e++)n[o.up[e]]=[0,-1*t]},_setZoomOffset:function(t){var e,i,n=this._zoomKeys={},o=this.keyCodes;for(e=0,i=o.zoomIn.length;i>e;e++)n[o.zoomIn[e]]=t;for(e=0,i=o.zoomOut.length;i>e;e++)n[o.zoomOut[e]]=-t},_addHooks:function(){o.DomEvent.on(e,"keydown",this._onKeyDown,this)},_removeHooks:function(){o.DomEvent.off(e,"keydown",this._onKeyDown,this)},_onKeyDown:function(t){var e=t.keyCode,i=this._map;if(e in this._panKeys){if(i._panAnim&&i._panAnim._inProgress)return;i.panBy(this._panKeys[e]),i.options.maxBounds&&i.panInsideBounds(i.options.maxBounds)}else{if(!(e in this._zoomKeys))return;i.setZoom(i.getZoom()+this._zoomKeys[e])}o.DomEvent.stop(t)}}),o.Map.addInitHook("addHandler","keyboard",o.Map.Keyboard),o.Handler.MarkerDrag=o.Handler.extend({initialize:function(t){this._marker=t},addHooks:function(){var t=this._marker._icon;this._draggable||(this._draggable=new o.Draggable(t,t)),this._draggable.on("dragstart",this._onDragStart,this).on("drag",this._onDrag,this).on("dragend",this._onDragEnd,this),this._draggable.enable(),o.DomUtil.addClass(this._marker._icon,"leaflet-marker-draggable")},removeHooks:function(){this._draggable.off("dragstart",this._onDragStart,this).off("drag",this._onDrag,this).off("dragend",this._onDragEnd,this),this._draggable.disable(),o.DomUtil.removeClass(this._marker._icon,"leaflet-marker-draggable")},moved:function(){return this._draggable&&this._draggable._moved},_onDragStart:function(){this._marker.closePopup().fire("movestart").fire("dragstart")},_onDrag:function(){var t=this._marker,e=t._shadow,i=o.DomUtil.getPosition(t._icon),n=t._map.layerPointToLatLng(i);e&&o.DomUtil.setPosition(e,i),t._latlng=n,t.fire("move",{latlng:n}).fire("drag")},_onDragEnd:function(t){this._marker.fire("moveend").fire("dragend",t)}}),o.Control=o.Class.extend({options:{position:"topright"},initialize:function(t){o.setOptions(this,t)},getPosition:function(){return this.options.position},setPosition:function(t){var e=this._map;return e&&e.removeControl(this),this.options.position=t,e&&e.addControl(this),this},getContainer:function(){return this._container},addTo:function(t){this._map=t;var e=this._container=this.onAdd(t),i=this.getPosition(),n=t._controlCorners[i];return o.DomUtil.addClass(e,"leaflet-control"),-1!==i.indexOf("bottom")?n.insertBefore(e,n.firstChild):n.appendChild(e),this},removeFrom:function(t){var e=this.getPosition(),i=t._controlCorners[e];return i.removeChild(this._container),this._map=null,this.onRemove&&this.onRemove(t),this},_refocusOnMap:function(){this._map&&this._map.getContainer().focus()}}),o.control=function(t){return new o.Control(t)},o.Map.include({addControl:function(t){return t.addTo(this),this},removeControl:function(t){return t.removeFrom(this),this},_initControlPos:function(){function t(t,s){var a=i+t+" "+i+s;e[t+s]=o.DomUtil.create("div",a,n)}var e=this._controlCorners={},i="leaflet-",n=this._controlContainer=o.DomUtil.create("div",i+"control-container",this._container);t("top","left"),t("top","right"),t("bottom","left"),t("bottom","right")},_clearControlPos:function(){this._container.removeChild(this._controlContainer)}}),o.Control.Zoom=o.Control.extend({options:{position:"topleft",zoomInText:"+",zoomInTitle:"Zoom in",zoomOutText:"-",zoomOutTitle:"Zoom out"},onAdd:function(t){var e="leaflet-control-zoom",i=o.DomUtil.create("div",e+" leaflet-bar");return this._map=t,this._zoomInButton=this._createButton(this.options.zoomInText,this.options.zoomInTitle,e+"-in",i,this._zoomIn,this),this._zoomOutButton=this._createButton(this.options.zoomOutText,this.options.zoomOutTitle,e+"-out",i,this._zoomOut,this),this._updateDisabled(),t.on("zoomend zoomlevelschange",this._updateDisabled,this),i},onRemove:function(t){t.off("zoomend zoomlevelschange",this._updateDisabled,this)},_zoomIn:function(t){this._map.zoomIn(t.shiftKey?3:1)},_zoomOut:function(t){this._map.zoomOut(t.shiftKey?3:1)},_createButton:function(t,e,i,n,s,a){var r=o.DomUtil.create("a",i,n);r.innerHTML=t,r.href="#",r.title=e;var h=o.DomEvent.stopPropagation;return o.DomEvent.on(r,"click",h).on(r,"mousedown",h).on(r,"dblclick",h).on(r,"click",o.DomEvent.preventDefault).on(r,"click",s,a).on(r,"click",this._refocusOnMap,a),r},_updateDisabled:function(){var t=this._map,e="leaflet-disabled";o.DomUtil.removeClass(this._zoomInButton,e),o.DomUtil.removeClass(this._zoomOutButton,e),t._zoom===t.getMinZoom()&&o.DomUtil.addClass(this._zoomOutButton,e),t._zoom===t.getMaxZoom()&&o.DomUtil.addClass(this._zoomInButton,e)}}),o.Map.mergeOptions({zoomControl:!0}),o.Map.addInitHook(function(){this.options.zoomControl&&(this.zoomControl=new o.Control.Zoom,this.addControl(this.zoomControl))}),o.control.zoom=function(t){return new o.Control.Zoom(t)},o.Control.Attribution=o.Control.extend({options:{position:"bottomright",prefix:'Leaflet'},initialize:function(t){o.setOptions(this,t),this._attributions={}},onAdd:function(t){this._container=o.DomUtil.create("div","leaflet-control-attribution"),o.DomEvent.disableClickPropagation(this._container);for(var e in t._layers)t._layers[e].getAttribution&&this.addAttribution(t._layers[e].getAttribution());return t.on("layeradd",this._onLayerAdd,this).on("layerremove",this._onLayerRemove,this),this._update(),this._container},onRemove:function(t){t.off("layeradd",this._onLayerAdd).off("layerremove",this._onLayerRemove)},setPrefix:function(t){return this.options.prefix=t,this._update(),this},addAttribution:function(t){return t?(this._attributions[t]||(this._attributions[t]=0),this._attributions[t]++,this._update(),this):void 0},removeAttribution:function(t){return t?(this._attributions[t]&&(this._attributions[t]--,this._update()),this):void 0},_update:function(){if(this._map){var t=[];for(var e in this._attributions)this._attributions[e]&&t.push(e);var i=[];this.options.prefix&&i.push(this.options.prefix),t.length&&i.push(t.join(", ")),this._container.innerHTML=i.join(" | ")}},_onLayerAdd:function(t){t.layer.getAttribution&&this.addAttribution(t.layer.getAttribution())},_onLayerRemove:function(t){t.layer.getAttribution&&this.removeAttribution(t.layer.getAttribution())}}),o.Map.mergeOptions({attributionControl:!0}),o.Map.addInitHook(function(){this.options.attributionControl&&(this.attributionControl=(new o.Control.Attribution).addTo(this))}),o.control.attribution=function(t){return new o.Control.Attribution(t)},o.Control.Scale=o.Control.extend({options:{position:"bottomleft",maxWidth:100,metric:!0,imperial:!0,updateWhenIdle:!1},onAdd:function(t){this._map=t;var e="leaflet-control-scale",i=o.DomUtil.create("div",e),n=this.options;return this._addScales(n,e,i),t.on(n.updateWhenIdle?"moveend":"move",this._update,this),t.whenReady(this._update,this),i},onRemove:function(t){t.off(this.options.updateWhenIdle?"moveend":"move",this._update,this)},_addScales:function(t,e,i){t.metric&&(this._mScale=o.DomUtil.create("div",e+"-line",i)),t.imperial&&(this._iScale=o.DomUtil.create("div",e+"-line",i))},_update:function(){var t=this._map.getBounds(),e=t.getCenter().lat,i=6378137*Math.PI*Math.cos(e*Math.PI/180),n=i*(t.getNorthEast().lng-t.getSouthWest().lng)/180,o=this._map.getSize(),s=this.options,a=0;o.x>0&&(a=n*(s.maxWidth/o.x)),this._updateScales(s,a)},_updateScales:function(t,e){t.metric&&e&&this._updateMetric(e),t.imperial&&e&&this._updateImperial(e)},_updateMetric:function(t){var e=this._getRoundNum(t);this._mScale.style.width=this._getScaleWidth(e/t)+"px",this._mScale.innerHTML=1e3>e?e+" m":e/1e3+" km"},_updateImperial:function(t){var e,i,n,o=3.2808399*t,s=this._iScale;o>5280?(e=o/5280,i=this._getRoundNum(e),s.style.width=this._getScaleWidth(i/e)+"px",s.innerHTML=i+" mi"):(n=this._getRoundNum(o),s.style.width=this._getScaleWidth(n/o)+"px",s.innerHTML=n+" ft")},_getScaleWidth:function(t){return Math.round(this.options.maxWidth*t)-10},_getRoundNum:function(t){var e=Math.pow(10,(Math.floor(t)+"").length-1),i=t/e;return i=i>=10?10:i>=5?5:i>=3?3:i>=2?2:1,e*i}}),o.control.scale=function(t){return new o.Control.Scale(t)},o.Control.Layers=o.Control.extend({options:{collapsed:!0,position:"topright",autoZIndex:!0},initialize:function(t,e,i){o.setOptions(this,i),this._layers={},this._lastZIndex=0,this._handlingClick=!1;for(var n in t)this._addLayer(t[n],n);for(n in e)this._addLayer(e[n],n,!0)},onAdd:function(t){return this._initLayout(),this._update(),t.on("layeradd",this._onLayerChange,this).on("layerremove",this._onLayerChange,this),this._container},onRemove:function(t){t.off("layeradd",this._onLayerChange,this).off("layerremove",this._onLayerChange,this)},addBaseLayer:function(t,e){return this._addLayer(t,e),this._update(),this},addOverlay:function(t,e){return this._addLayer(t,e,!0),this._update(),this},removeLayer:function(t){var e=o.stamp(t);return delete this._layers[e],this._update(),this},_initLayout:function(){var t="leaflet-control-layers",e=this._container=o.DomUtil.create("div",t);e.setAttribute("aria-haspopup",!0),o.Browser.touch?o.DomEvent.on(e,"click",o.DomEvent.stopPropagation):o.DomEvent.disableClickPropagation(e).disableScrollPropagation(e);var i=this._form=o.DomUtil.create("form",t+"-list");if(this.options.collapsed){o.Browser.android||o.DomEvent.on(e,"mouseover",this._expand,this).on(e,"mouseout",this._collapse,this);var n=this._layersLink=o.DomUtil.create("a",t+"-toggle",e);n.href="#",n.title="Layers",o.Browser.touch?o.DomEvent.on(n,"click",o.DomEvent.stop).on(n,"click",this._expand,this):o.DomEvent.on(n,"focus",this._expand,this),o.DomEvent.on(i,"click",function(){setTimeout(o.bind(this._onInputClick,this),0)},this),this._map.on("click",this._collapse,this)}else this._expand();this._baseLayersList=o.DomUtil.create("div",t+"-base",i),this._separator=o.DomUtil.create("div",t+"-separator",i),this._overlaysList=o.DomUtil.create("div",t+"-overlays",i),e.appendChild(i)},_addLayer:function(t,e,i){var n=o.stamp(t);this._layers[n]={layer:t,name:e,overlay:i},this.options.autoZIndex&&t.setZIndex&&(this._lastZIndex++,t.setZIndex(this._lastZIndex))},_update:function(){if(this._container){this._baseLayersList.innerHTML="",this._overlaysList.innerHTML="";var t,e,i=!1,n=!1;for(t in this._layers)e=this._layers[t],this._addItem(e),n=n||e.overlay,i=i||!e.overlay;this._separator.style.display=n&&i?"":"none"}},_onLayerChange:function(t){var e=this._layers[o.stamp(t.layer)];if(e){this._handlingClick||this._update();var i=e.overlay?"layeradd"===t.type?"overlayadd":"overlayremove":"layeradd"===t.type?"baselayerchange":null;i&&this._map.fire(i,e)}},_createRadioElement:function(t,i){var n='t;t++)e=n[t],i=this._layers[e.layerId],e.checked&&!this._map.hasLayer(i.layer)?this._map.addLayer(i.layer):!e.checked&&this._map.hasLayer(i.layer)&&this._map.removeLayer(i.layer);this._handlingClick=!1,this._refocusOnMap()},_expand:function(){o.DomUtil.addClass(this._container,"leaflet-control-layers-expanded")},_collapse:function(){this._container.className=this._container.className.replace(" leaflet-control-layers-expanded","")}}),o.control.layers=function(t,e,i){return new o.Control.Layers(t,e,i)},o.PosAnimation=o.Class.extend({includes:o.Mixin.Events,run:function(t,e,i,n){this.stop(),this._el=t,this._inProgress=!0,this._newPos=e,this.fire("start"),t.style[o.DomUtil.TRANSITION]="all "+(i||.25)+"s cubic-bezier(0,0,"+(n||.5)+",1)",o.DomEvent.on(t,o.DomUtil.TRANSITION_END,this._onTransitionEnd,this),o.DomUtil.setPosition(t,e),o.Util.falseFn(t.offsetWidth),this._stepTimer=setInterval(o.bind(this._onStep,this),50)},stop:function(){this._inProgress&&(o.DomUtil.setPosition(this._el,this._getPos()),this._onTransitionEnd(),o.Util.falseFn(this._el.offsetWidth))},_onStep:function(){var t=this._getPos();return t?(this._el._leaflet_pos=t,void this.fire("step")):void this._onTransitionEnd()},_transformRe:/([-+]?(?:\d*\.)?\d+)\D*, ([-+]?(?:\d*\.)?\d+)\D*\)/,_getPos:function(){var e,i,n,s=this._el,a=t.getComputedStyle(s);if(o.Browser.any3d){if(n=a[o.DomUtil.TRANSFORM].match(this._transformRe),!n)return;e=parseFloat(n[1]),i=parseFloat(n[2])}else e=parseFloat(a.left),i=parseFloat(a.top);return new o.Point(e,i,!0)},_onTransitionEnd:function(){o.DomEvent.off(this._el,o.DomUtil.TRANSITION_END,this._onTransitionEnd,this),this._inProgress&&(this._inProgress=!1,this._el.style[o.DomUtil.TRANSITION]="",this._el._leaflet_pos=this._newPos,clearInterval(this._stepTimer),this.fire("step").fire("end"))}}),o.Map.include({setView:function(t,e,n){if(e=e===i?this._zoom:this._limitZoom(e),t=this._limitCenter(o.latLng(t),e,this.options.maxBounds),n=n||{},this._panAnim&&this._panAnim.stop(),this._loaded&&!n.reset&&n!==!0){n.animate!==i&&(n.zoom=o.extend({animate:n.animate},n.zoom),n.pan=o.extend({animate:n.animate},n.pan));var s=this._zoom!==e?this._tryAnimatedZoom&&this._tryAnimatedZoom(t,e,n.zoom):this._tryAnimatedPan(t,n.pan);if(s)return clearTimeout(this._sizeTimer),this}return this._resetView(t,e),this},panBy:function(t,e){if(t=o.point(t).round(),e=e||{},!t.x&&!t.y)return this;if(this._panAnim||(this._panAnim=new o.PosAnimation,this._panAnim.on({step:this._onPanTransitionStep,end:this._onPanTransitionEnd},this)),e.noMoveStart||this.fire("movestart"),e.animate!==!1){o.DomUtil.addClass(this._mapPane,"leaflet-pan-anim");var i=this._getMapPanePos().subtract(t);this._panAnim.run(this._mapPane,i,e.duration||.25,e.easeLinearity)}else this._rawPanBy(t),this.fire("move").fire("moveend");return this},_onPanTransitionStep:function(){this.fire("move")},_onPanTransitionEnd:function(){o.DomUtil.removeClass(this._mapPane,"leaflet-pan-anim"),this.fire("moveend")},_tryAnimatedPan:function(t,e){var i=this._getCenterOffset(t)._floor();return(e&&e.animate)===!0||this.getSize().contains(i)?(this.panBy(i,e),!0):!1}}),o.PosAnimation=o.DomUtil.TRANSITION?o.PosAnimation:o.PosAnimation.extend({run:function(t,e,i,n){this.stop(),this._el=t,this._inProgress=!0,this._duration=i||.25,this._easeOutPower=1/Math.max(n||.5,.2),this._startPos=o.DomUtil.getPosition(t),this._offset=e.subtract(this._startPos),this._startTime=+new Date,this.fire("start"),this._animate()},stop:function(){this._inProgress&&(this._step(),this._complete())},_animate:function(){this._animId=o.Util.requestAnimFrame(this._animate,this),this._step()},_step:function(){var t=+new Date-this._startTime,e=1e3*this._duration;e>t?this._runFrame(this._easeOut(t/e)):(this._runFrame(1),this._complete())},_runFrame:function(t){var e=this._startPos.add(this._offset.multiplyBy(t));o.DomUtil.setPosition(this._el,e),this.fire("step")},_complete:function(){o.Util.cancelAnimFrame(this._animId),this._inProgress=!1,this.fire("end")},_easeOut:function(t){return 1-Math.pow(1-t,this._easeOutPower)}}),o.Map.mergeOptions({zoomAnimation:!0,zoomAnimationThreshold:4}),o.DomUtil.TRANSITION&&o.Map.addInitHook(function(){this._zoomAnimated=this.options.zoomAnimation&&o.DomUtil.TRANSITION&&o.Browser.any3d&&!o.Browser.android23&&!o.Browser.mobileOpera,this._zoomAnimated&&o.DomEvent.on(this._mapPane,o.DomUtil.TRANSITION_END,this._catchTransitionEnd,this)}),o.Map.include(o.DomUtil.TRANSITION?{_catchTransitionEnd:function(t){this._animatingZoom&&t.propertyName.indexOf("transform")>=0&&this._onZoomTransitionEnd()},_nothingToAnimate:function(){return!this._container.getElementsByClassName("leaflet-zoom-animated").length},_tryAnimatedZoom:function(t,e,i){if(this._animatingZoom)return!0;if(i=i||{},!this._zoomAnimated||i.animate===!1||this._nothingToAnimate()||Math.abs(e-this._zoom)>this.options.zoomAnimationThreshold)return!1;var n=this.getZoomScale(e),o=this._getCenterOffset(t)._divideBy(1-1/n),s=this._getCenterLayerPoint()._add(o);return i.animate===!0||this.getSize().contains(o)?(this.fire("movestart").fire("zoomstart"),this._animateZoom(t,e,s,n,null,!0),!0):!1},_animateZoom:function(t,e,i,n,s,a,r){r||(this._animatingZoom=!0),o.DomUtil.addClass(this._mapPane,"leaflet-zoom-anim"),this._animateToCenter=t,this._animateToZoom=e,o.Draggable&&(o.Draggable._disabled=!0),o.Util.requestAnimFrame(function(){this.fire("zoomanim",{center:t,zoom:e,origin:i,scale:n,delta:s,backwards:a}),setTimeout(o.bind(this._onZoomTransitionEnd,this),250)},this)},_onZoomTransitionEnd:function(){this._animatingZoom&&(this._animatingZoom=!1,o.DomUtil.removeClass(this._mapPane,"leaflet-zoom-anim"),o.Util.requestAnimFrame(function(){this._resetView(this._animateToCenter,this._animateToZoom,!0,!0),o.Draggable&&(o.Draggable._disabled=!1)},this))}}:{}),o.TileLayer.include({_animateZoom:function(t){this._animating||(this._animating=!0,this._prepareBgBuffer());var e=this._bgBuffer,i=o.DomUtil.TRANSFORM,n=t.delta?o.DomUtil.getTranslateString(t.delta):e.style[i],s=o.DomUtil.getScaleString(t.scale,t.origin);e.style[i]=t.backwards?s+" "+n:n+" "+s},_endZoomAnim:function(){var t=this._tileContainer,e=this._bgBuffer;t.style.visibility="",t.parentNode.appendChild(t),o.Util.falseFn(e.offsetWidth);var i=this._map.getZoom();(i>this.options.maxZoom||i.5&&.5>n?(t.style.visibility="hidden",void this._stopLoadingImages(t)):(e.style.visibility="hidden",e.style[o.DomUtil.TRANSFORM]="",this._tileContainer=e,e=this._bgBuffer=t,this._stopLoadingImages(e),void clearTimeout(this._clearBgBufferTimer))},_getLoadedTilesPercentage:function(t){var e,i,n=t.getElementsByTagName("img"),o=0;for(e=0,i=n.length;i>e;e++)n[e].complete&&o++;return o/i},_stopLoadingImages:function(t){var e,i,n,s=Array.prototype.slice.call(t.getElementsByTagName("img"));for(e=0,i=s.length;i>e;e++)n=s[e],n.complete||(n.onload=o.Util.falseFn,n.onerror=o.Util.falseFn,n.src=o.Util.emptyImageUrl,n.parentNode.removeChild(n))}}),o.Map.include({_defaultLocateOptions:{watch:!1,setView:!1,maxZoom:1/0,timeout:1e4,maximumAge:0,enableHighAccuracy:!1},locate:function(t){if(t=this._locateOptions=o.extend(this._defaultLocateOptions,t),!navigator.geolocation)return this._handleGeolocationError({code:0,message:"Geolocation not supported."}),this;var e=o.bind(this._handleGeolocationResponse,this),i=o.bind(this._handleGeolocationError,this);return t.watch?this._locationWatchId=navigator.geolocation.watchPosition(e,i,t):navigator.geolocation.getCurrentPosition(e,i,t),this},stopLocate:function(){return navigator.geolocation&&navigator.geolocation.clearWatch(this._locationWatchId),this._locateOptions&&(this._locateOptions.setView=!1),this},_handleGeolocationError:function(t){var e=t.code,i=t.message||(1===e?"permission denied":2===e?"position unavailable":"timeout");this._locateOptions.setView&&!this._loaded&&this.fitWorld(),this.fire("locationerror",{code:e,message:"Geolocation error: "+i+"."})},_handleGeolocationResponse:function(t){var e=t.coords.latitude,i=t.coords.longitude,n=new o.LatLng(e,i),s=180*t.coords.accuracy/40075017,a=s/Math.cos(o.LatLng.DEG_TO_RAD*e),r=o.latLngBounds([e-s,i-a],[e+s,i+a]),h=this._locateOptions;if(h.setView){var l=Math.min(this.getBoundsZoom(r),h.maxZoom);this.setView(n,l)}var u={latlng:n,bounds:r,timestamp:t.timestamp};for(var c in t.coords)"number"==typeof t.coords[c]&&(u[c]=t.coords[c]);this.fire("locationfound",u)}})}(window,document); \ No newline at end of file diff --git a/www/manual_lib/leaflet/images/layers-2x.png b/www/manual_lib/leaflet/images/layers-2x.png new file mode 100644 index 0000000000000000000000000000000000000000..200c333dca9652ac4cba004d609e5af4eee168c1 GIT binary patch literal 1259 zcmVFhCYNy;#0irRPomHqW|G1C*;4?@4#E?jH>?v@U%cy?3dQAc-DchXVErpOh~ z-jbon+tNbnl6hoEb;)TVk+%hTDDi_G%i3*RZ&15!$Fjr^f;Ke&A@|?=`2&+{zr+3a z{D*=t(`AXyS%X7N z%a#RZw6vD^t_rnM`L4E>m=U&R!A-&}nZIi$BOPvkhrCuUe@BN~-lRD)f44;J%TwgE zcze8u!PQ_NR7?o(NylLXVTfDO zxs5=@|GsYEsNo4M#nT%N!UE(?dnS)t2+{ELYAFp*3=iF=|EQnTp`#vlSXuGVraYo? z+RCzXo6h3qA8{KG?S4nE(lM+;Eb4nT3XV;7gcAxUi5m)`k5tv}cPy()8ZR3TLW3I- zAS^}cq-IJvL7a4RgR!yk@~RT%$lA7{L5ES*hyx)M4(yxI$Ub(4f)K|^v1>zvwQY!_ zIrWw8q9GS^!Dp~}+?mbnB6jDF8mVlbQ!jFKDY;w=7;XO{9bq7>LXGK24WA`;rL)_Z z)&j}pbV(;6gY;VMhbxgvn`X;6x}VUEE-7 z%)7j-%t8S=ZL3yc)HbXDAqJZvBTPoiW_A-+a8m3_Z?v{DN7Tnr#O_VUMT0UBt$;p` zDh6JbGHN8JJ*JN%y2%msb97@_S>9!%Egwk;?PEkU9ntz&3uR}%Fj5d$JHQbQb3}a{ zSzFT^#n=VInPpcAS}CNxj?_ zVscANk5Cfz(51EI1pz};AWWb|kgbYNb4wCEGUn3+eMUMV?1-{=I4TlmLJMot@rd07 zZuo2hk1ccu{YmGkcYdWAVdk{Z4Nm?^cTD&}jGm+Q1SYIXMwmG*oO*83&#>l%nbR`G zhh=lZ%xIb7kU3#;TBbfECrnC9P=-XpL|TG2BoZdj61*XiFbW8?1Z_wp%#;>${SUIy V$8qr;L*)Pf002ovPDHLkV1hYLS~36t literal 0 HcmV?d00001 diff --git a/www/manual_lib/leaflet/images/layers.png b/www/manual_lib/leaflet/images/layers.png new file mode 100644 index 0000000000000000000000000000000000000000..1a72e5784b2b456eac5d7670738db80697af3377 GIT binary patch literal 696 zcmV;p0!RIcP)*@&l2<6p=!C&s@#ZL+%BQvF&b?w6S%wp=I>1QHj7AP5C)IWy#b znXXB;g;j=$a-tW89K%FbDceHVq&unY*Wx3L#=EGWH=rjqnp|4c_Ulec!ql3#G-5ZF zVlbBA@XP=)C8U&+Lrc)S4O5%1$&{(;7R^K(CSnvSr$v;+B$8q&7Bf|h$#PARo1^%M zf1H^nG-EiXVXr07OH(*8R)xa|FD;lXUlg_-%)~ZGsL2cX0NXaAzN2q%jqLRR6ruVk8`Jb7n#{`T;o@`F= z#3YcynIR^s83UNF3D!f5m#Mg)NJ24&Qfrqb&_z=yF;=B)#9Iq7u-@^O!(mW{D;qvr zPc)gVb%aowtS8m@ElL4A9G>w#ffQ~q{i&_i)*6f^)Sz|C?C>zb4Uo?H<-&Hz@a?J; z$ml@zGygWofb9$ZBj6aLjpLhsT2AzjOu=-*u_gSCUYnU^5s62$4H-fe}gSR(=wKRaTHh!@*b)YV6mo|a4Fn6Rgc&Rpk zvn_X|3VY?v=>nJ{slE^V1GaGWk}m@aIWGIpghbfPh8m@aIWEo_%AZI>==moIFVE^L=C zZJ91?mo03UEp3-BY?wBGur6$uD{Yr9Y?m%SHF8Fk1pc(Nva%QJ+{FLkalfypz3&M|||Fn`7|g3c~4(nXHKFmRnwn$J#_$xE8i z|Ns9!kC;(oC1qQk>LMp3_a2(odYyMT@>voX=UI)k>1cJdn;gjmJ-|6v4nb1Oryh)eQMwHP(i@!36%vGJyFK(JTj?Vb{{C=jx&)@1l zlFmnw%0`&bqruifkkHKC=vbiAM3&E`#Mv>2%tw;VK8?_|&E89cs{a1}$J*!f_xd-C z&F%B|oxRgPlh0F!txkxrQjNA`m9~?&&|jw4W0<`_iNHsX$VQXVK!B}Xkh4>av|f_8 zLY2?t?ejE=%(TnfV5iqOjm?d;&qI~ZGl|SzU77a)002XDQchC<95+*MjE@82?VLm= z3xf6%Vd@99z|q|-ua5l3kJxvZwan-8K1cPiwQAtlcNX~ZqLeoMB+a;7)WA|O#HOB% zg6SX;754xD1{Fy}K~#8Ntklac&zTpadXZ& zC*_=T&g7hfbI$R?v%9?sknIb97gJOJ=`-8YyS3ndqN+Jm+x33!p&Hc@@L$w))s2@N ztv~i}Emc?DykgwFWwma($8+~b>l?tqj$dh13R^nMZnva9 zn0Vflzv2Dvp`oVQw{Guby~i`JGbyBGTEC{y>yzCkg>K&CIeQ$u;lyQ+M{O~gEJ^)Z zrF3p)^>|uT;57}WY&IRwyOQ=dq%Az}_t=_hKowP!Z79q0;@Zu(SWEJJcHY+5T6I({ zw)wj*SNi4wrd+POUfZe4gF77vW?j zoFS}|r2n&$U9Y!S4VEOyN}OpZZi|?cr1VcE_tHsDQgp-ga(SwkBrkCm{|*-yb=}ZW zvcYvLvfA90TPn|!-TuYJV<6`}+RJeRgP3EA=qQcF9k0*#*{f&I_pjam%I6Dd#YE|G zqB!R}tW-K!wV1w+4JcFA_s6~=@9F&j8`u$-ifLN3vK;`lvaA-`jRn_}(8|)!3?-}I zvFi{H;@A$gEZYh?%|Qr_y#*UkOPjwiRCsJQ>mb6h5yGIk6C5_XA=8T?IBfm_?+P0; zhhUs)-(0R*H<&Kku(1>#cGtOpk&Z&kQcw&SJv-4VY<+;=8hYnoX zfNJMCa9)^5Z0;2dCUk;x-%#yS!I~Jr3pNuI!g_tHz!$hKwt1GL~sFvx)3u4TA zv>CLGdQtoZ7Du7ctJRfTqY;FPxs1G{ZJ?73D5J@OO{6BHcPbk{_mjg&p2QFeke%QI zlAJ-kvjuwy1<5D-6>su68A+i998aSZNnQX)+Q}6(GK-C%8G-!1bOJBONU{gT%IOOE z;Yk24YC@^lFW77>r6x7eS1Omc;8=GUp#&zLQ&L{ zv8$hGC`wp~$9pR>f%-_Ps3>YhzP(+vC(E*zr1CVO8ChN^MI-VGMX7+|(r!SGZ9gd5 zzO9sQd>sm|f1|X&oh=8lOzd6+ITvo zCXInR?>RZ#>Hb*PO=7dI!dZ(wY4O}ZGv zdfQFio7+0~PN*RFCZGM6@9-o~y*@?;k00NvOsw54t1^tt{*ATMs^2j}4Wp=4t3RH* z_+8b`F-{E=0sOgM<;VHTo!Ij3u zmmI`2?K7g(GOcGA)@h?$SW&pwHdtj1n57PLI8&6RHhx4R%Q7b z^JEqR)@06V!pbS*@D_ZyRMo_LlT}r{#sXOx4kM-V<_V{!5SSuM^SIVCA37|nY7LWQ zZA#B1h4l`6asz=Lvax_#GMRX|NF>=$=p{Qn0i@ExX1jGhy@B8a*_uR+ODEbVi8ObL zezG?azy>E~S~dl43&8<$(2H}P&*tuBdESUP83KQ?8B z?K(!uS>H1wlWQz;qOfB`T#TZ=EoSp~vZ5XtCvwm1h*Ex6mzTsn_y@_=xREIslV-%- zpdWkEzMjeNOGWrSM32gpBt27*O29NdhGzuDgYxcf`Jjjqw@B;Vmdb@fxdhCRi`Kg> zmUTr$=&@#i!%F4Q6mb&4QKfR^95KJ!<6~fqx-f^66AV!|ywG{6D^Vay-3b99>XOe# e-I|>x8~*?ZhF3snGbtJX0000cOl4 literal 0 HcmV?d00001 diff --git a/www/manual_lib/leaflet/images/marker-icon.png b/www/manual_lib/leaflet/images/marker-icon.png new file mode 100644 index 0000000000000000000000000000000000000000..950edf24677ded147df13b26f91baa2b0fa70513 GIT binary patch literal 1466 zcmV;r1x5OaP)P001cn1^@s6z>|W`000GnNklGNuHDcIX17Zdjl&3`L?0sTjIws<{((Dh&g-s0<@jYQyl?D*X^?%13;ml^gy> ziMrY_^1WI=(g@LMizu=zCoA>C`6|QEq1eV92k*7m>G65*&@&6)aC&e}G zI)pf-Za|N`DT&Cn1J|o`19mumxW~hiKiKyc-P`S@q)rdTo84@QI@;0yXrG%9uhI>A zG5QHb6s4=<6xy{1 z@NMxEkryp{LS44%z$3lP^cX!9+2-;CTt3wM4(k*#C{aiIiLuB>jJj;KPhPzIC00bL zU3a#;aJld94lCW=`4&aAy8M7PY=HQ>O%$YEP4c4UY#CRxfgbE~(|uiI=YS8q;O9y6 zmIkXzR`}p7ti|PrM3a}WMnR=3NVnWdAAR>b9X@)DKL6=YsvmH%?I24wdq?Gh54_;# z$?_LvgjEdspdQlft#4CQ z`2Zyvy?*)N1Ftw|{_hakhG9WjS?Az@I@+IZ8JbWewR!XUK4&6346+d#~gsE0SY(LX8&JfY>Aj)RxGy96nwhs2rv zzW6pTnMpFkDSkT*a*6Dx|u@ds6ISVn0@^RmIsKZ5Y;bazbc;tTSq(kg(=481ODrPyNB6n z-$+U}(w$m6U6H$w17Bw+wDaFIe~GvNMYvnw31MpY0eQKT9l>SU``8k7w4)z!GZKMI z#_cEKq7k~i%nlK@6c-K?+R;B#5$?T#YpKD`t_4bAs^#E+@5QW$@OX3*`;(#{U^d-vY)&xEE>n5lYl&T?Amke9$Lam@{1K@O ze*LXqlKQHiv=gx+V^Cbb2?z@ISBQ*3amF;9UJ3SBg(N|710TLamQmYZ&Qjn2LuO<* zCZlB4n%@pc&7NNnY1}x+NWpHlq`OJEo|`aYN9<`RBUB+79g;>dgb6YlfN#kGL?lO_ z!6~M^7sOnbsUkKk<@Ysie&`G>ruxH&Mgy&8;i=A zB9OO!xR{AyODw>DS-q5YM{0ExFEAzt zm>RdS+ssW(-8|?xr0(?$vBVB*%(xDLtq3Hf0I5yFm<_g=W2`QWAax{1rWVH=I!VrP zs(rTFX@W#t$hXNvbgX`gK&^w_YD;CQ!B@e0QbLIWaKAXQe2-kkloo;{iF#6}z!4=W zi$giRj1{ zt;2w`VSCF#WE&*ev7jpsC=6175@(~nTE2;7M-L((0bH@yG}-TB$R~WXd?tA$s3|%y zA`9$sA(>F%J3ioz<-LJl*^o1|w84l>HBR`>3l9c8$5Xr@xCiIQ7{x$fMCzOk_-M=% z+{a_Q#;42`#KfUte@$NT77uaTz?b-fBe)1s5XE$yA79fm?KqM^VgLXD07*qoM6N<$ Ef<_J(9smFU literal 0 HcmV?d00001 diff --git a/www/manual_lib/leaflet/leaflet-src.esm.js b/www/manual_lib/leaflet/leaflet-src.esm.js new file mode 100644 index 000000000..a967bd7d3 --- /dev/null +++ b/www/manual_lib/leaflet/leaflet-src.esm.js @@ -0,0 +1,14033 @@ +/* @preserve + * Leaflet 1.8.0, a JS library for interactive maps. https://leafletjs.com + * (c) 2010-2022 Vladimir Agafonkin, (c) 2010-2011 CloudMade + */ + +var version = "1.8.0"; + +/* + * @namespace Util + * + * Various utility functions, used by Leaflet internally. + */ + +// @function extend(dest: Object, src?: Object): Object +// Merges the properties of the `src` object (or multiple objects) into `dest` object and returns the latter. Has an `L.extend` shortcut. +function extend(dest) { + var i, j, len, src; + + for (j = 1, len = arguments.length; j < len; j++) { + src = arguments[j]; + for (i in src) { + dest[i] = src[i]; + } + } + return dest; +} + +// @function create(proto: Object, properties?: Object): Object +// Compatibility polyfill for [Object.create](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/create) +var create$2 = Object.create || (function () { + function F() {} + return function (proto) { + F.prototype = proto; + return new F(); + }; +})(); + +// @function bind(fn: Function, …): Function +// Returns a new function bound to the arguments passed, like [Function.prototype.bind](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function/bind). +// Has a `L.bind()` shortcut. +function bind(fn, obj) { + var slice = Array.prototype.slice; + + if (fn.bind) { + return fn.bind.apply(fn, slice.call(arguments, 1)); + } + + var args = slice.call(arguments, 2); + + return function () { + return fn.apply(obj, args.length ? args.concat(slice.call(arguments)) : arguments); + }; +} + +// @property lastId: Number +// Last unique ID used by [`stamp()`](#util-stamp) +var lastId = 0; + +// @function stamp(obj: Object): Number +// Returns the unique ID of an object, assigning it one if it doesn't have it. +function stamp(obj) { + if (!('_leaflet_id' in obj)) { + obj['_leaflet_id'] = ++lastId; + } + return obj._leaflet_id; +} + +// @function throttle(fn: Function, time: Number, context: Object): Function +// Returns a function which executes function `fn` with the given scope `context` +// (so that the `this` keyword refers to `context` inside `fn`'s code). The function +// `fn` will be called no more than one time per given amount of `time`. The arguments +// received by the bound function will be any arguments passed when binding the +// function, followed by any arguments passed when invoking the bound function. +// Has an `L.throttle` shortcut. +function throttle(fn, time, context) { + var lock, args, wrapperFn, later; + + later = function () { + // reset lock and call if queued + lock = false; + if (args) { + wrapperFn.apply(context, args); + args = false; + } + }; + + wrapperFn = function () { + if (lock) { + // called too soon, queue to call later + args = arguments; + + } else { + // call and lock until later + fn.apply(context, arguments); + setTimeout(later, time); + lock = true; + } + }; + + return wrapperFn; +} + +// @function wrapNum(num: Number, range: Number[], includeMax?: Boolean): Number +// Returns the number `num` modulo `range` in such a way so it lies within +// `range[0]` and `range[1]`. The returned value will be always smaller than +// `range[1]` unless `includeMax` is set to `true`. +function wrapNum(x, range, includeMax) { + var max = range[1], + min = range[0], + d = max - min; + return x === max && includeMax ? x : ((x - min) % d + d) % d + min; +} + +// @function falseFn(): Function +// Returns a function which always returns `false`. +function falseFn() { return false; } + +// @function formatNum(num: Number, precision?: Number|false): Number +// Returns the number `num` rounded with specified `precision`. +// The default `precision` value is 6 decimal places. +// `false` can be passed to skip any processing (can be useful to avoid round-off errors). +function formatNum(num, precision) { + if (precision === false) { return num; } + var pow = Math.pow(10, precision === undefined ? 6 : precision); + return Math.round(num * pow) / pow; +} + +// @function trim(str: String): String +// Compatibility polyfill for [String.prototype.trim](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/Trim) +function trim(str) { + return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, ''); +} + +// @function splitWords(str: String): String[] +// Trims and splits the string on whitespace and returns the array of parts. +function splitWords(str) { + return trim(str).split(/\s+/); +} + +// @function setOptions(obj: Object, options: Object): Object +// Merges the given properties to the `options` of the `obj` object, returning the resulting options. See `Class options`. Has an `L.setOptions` shortcut. +function setOptions(obj, options) { + if (!Object.prototype.hasOwnProperty.call(obj, 'options')) { + obj.options = obj.options ? create$2(obj.options) : {}; + } + for (var i in options) { + obj.options[i] = options[i]; + } + return obj.options; +} + +// @function getParamString(obj: Object, existingUrl?: String, uppercase?: Boolean): String +// Converts an object into a parameter URL string, e.g. `{a: "foo", b: "bar"}` +// translates to `'?a=foo&b=bar'`. If `existingUrl` is set, the parameters will +// be appended at the end. If `uppercase` is `true`, the parameter names will +// be uppercased (e.g. `'?A=foo&B=bar'`) +function getParamString(obj, existingUrl, uppercase) { + var params = []; + for (var i in obj) { + params.push(encodeURIComponent(uppercase ? i.toUpperCase() : i) + '=' + encodeURIComponent(obj[i])); + } + return ((!existingUrl || existingUrl.indexOf('?') === -1) ? '?' : '&') + params.join('&'); +} + +var templateRe = /\{ *([\w_ -]+) *\}/g; + +// @function template(str: String, data: Object): String +// Simple templating facility, accepts a template string of the form `'Hello {a}, {b}'` +// and a data object like `{a: 'foo', b: 'bar'}`, returns evaluated string +// `('Hello foo, bar')`. You can also specify functions instead of strings for +// data values — they will be evaluated passing `data` as an argument. +function template(str, data) { + return str.replace(templateRe, function (str, key) { + var value = data[key]; + + if (value === undefined) { + throw new Error('No value provided for variable ' + str); + + } else if (typeof value === 'function') { + value = value(data); + } + return value; + }); +} + +// @function isArray(obj): Boolean +// Compatibility polyfill for [Array.isArray](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray) +var isArray = Array.isArray || function (obj) { + return (Object.prototype.toString.call(obj) === '[object Array]'); +}; + +// @function indexOf(array: Array, el: Object): Number +// Compatibility polyfill for [Array.prototype.indexOf](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf) +function indexOf(array, el) { + for (var i = 0; i < array.length; i++) { + if (array[i] === el) { return i; } + } + return -1; +} + +// @property emptyImageUrl: String +// Data URI string containing a base64-encoded empty GIF image. +// Used as a hack to free memory from unused images on WebKit-powered +// mobile devices (by setting image `src` to this string). +var emptyImageUrl = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs='; + +// inspired by https://paulirish.com/2011/requestanimationframe-for-smart-animating/ + +function getPrefixed(name) { + return window['webkit' + name] || window['moz' + name] || window['ms' + name]; +} + +var lastTime = 0; + +// fallback for IE 7-8 +function timeoutDefer(fn) { + var time = +new Date(), + timeToCall = Math.max(0, 16 - (time - lastTime)); + + lastTime = time + timeToCall; + return window.setTimeout(fn, timeToCall); +} + +var requestFn = window.requestAnimationFrame || getPrefixed('RequestAnimationFrame') || timeoutDefer; +var cancelFn = window.cancelAnimationFrame || getPrefixed('CancelAnimationFrame') || + getPrefixed('CancelRequestAnimationFrame') || function (id) { window.clearTimeout(id); }; + +// @function requestAnimFrame(fn: Function, context?: Object, immediate?: Boolean): Number +// Schedules `fn` to be executed when the browser repaints. `fn` is bound to +// `context` if given. When `immediate` is set, `fn` is called immediately if +// the browser doesn't have native support for +// [`window.requestAnimationFrame`](https://developer.mozilla.org/docs/Web/API/window/requestAnimationFrame), +// otherwise it's delayed. Returns a request ID that can be used to cancel the request. +function requestAnimFrame(fn, context, immediate) { + if (immediate && requestFn === timeoutDefer) { + fn.call(context); + } else { + return requestFn.call(window, bind(fn, context)); + } +} + +// @function cancelAnimFrame(id: Number): undefined +// Cancels a previous `requestAnimFrame`. See also [window.cancelAnimationFrame](https://developer.mozilla.org/docs/Web/API/window/cancelAnimationFrame). +function cancelAnimFrame(id) { + if (id) { + cancelFn.call(window, id); + } +} + +var Util = { + __proto__: null, + extend: extend, + create: create$2, + bind: bind, + get lastId () { return lastId; }, + stamp: stamp, + throttle: throttle, + wrapNum: wrapNum, + falseFn: falseFn, + formatNum: formatNum, + trim: trim, + splitWords: splitWords, + setOptions: setOptions, + getParamString: getParamString, + template: template, + isArray: isArray, + indexOf: indexOf, + emptyImageUrl: emptyImageUrl, + requestFn: requestFn, + cancelFn: cancelFn, + requestAnimFrame: requestAnimFrame, + cancelAnimFrame: cancelAnimFrame +}; + +// @class Class +// @aka L.Class + +// @section +// @uninheritable + +// Thanks to John Resig and Dean Edwards for inspiration! + +function Class() {} + +Class.extend = function (props) { + + // @function extend(props: Object): Function + // [Extends the current class](#class-inheritance) given the properties to be included. + // Returns a Javascript function that is a class constructor (to be called with `new`). + var NewClass = function () { + + setOptions(this); + + // call the constructor + if (this.initialize) { + this.initialize.apply(this, arguments); + } + + // call all constructor hooks + this.callInitHooks(); + }; + + var parentProto = NewClass.__super__ = this.prototype; + + var proto = create$2(parentProto); + proto.constructor = NewClass; + + NewClass.prototype = proto; + + // inherit parent's statics + for (var i in this) { + if (Object.prototype.hasOwnProperty.call(this, i) && i !== 'prototype' && i !== '__super__') { + NewClass[i] = this[i]; + } + } + + // mix static properties into the class + if (props.statics) { + extend(NewClass, props.statics); + } + + // mix includes into the prototype + if (props.includes) { + checkDeprecatedMixinEvents(props.includes); + extend.apply(null, [proto].concat(props.includes)); + } + + // mix given properties into the prototype + extend(proto, props); + delete proto.statics; + delete proto.includes; + + // merge options + if (proto.options) { + proto.options = parentProto.options ? create$2(parentProto.options) : {}; + extend(proto.options, props.options); + } + + proto._initHooks = []; + + // add method for calling all hooks + proto.callInitHooks = function () { + + if (this._initHooksCalled) { return; } + + if (parentProto.callInitHooks) { + parentProto.callInitHooks.call(this); + } + + this._initHooksCalled = true; + + for (var i = 0, len = proto._initHooks.length; i < len; i++) { + proto._initHooks[i].call(this); + } + }; + + return NewClass; +}; + + +// @function include(properties: Object): this +// [Includes a mixin](#class-includes) into the current class. +Class.include = function (props) { + var parentOptions = this.prototype.options; + extend(this.prototype, props); + if (props.options) { + this.prototype.options = parentOptions; + this.mergeOptions(props.options); + } + return this; +}; + +// @function mergeOptions(options: Object): this +// [Merges `options`](#class-options) into the defaults of the class. +Class.mergeOptions = function (options) { + extend(this.prototype.options, options); + return this; +}; + +// @function addInitHook(fn: Function): this +// Adds a [constructor hook](#class-constructor-hooks) to the class. +Class.addInitHook = function (fn) { // (Function) || (String, args...) + var args = Array.prototype.slice.call(arguments, 1); + + var init = typeof fn === 'function' ? fn : function () { + this[fn].apply(this, args); + }; + + this.prototype._initHooks = this.prototype._initHooks || []; + this.prototype._initHooks.push(init); + return this; +}; + +function checkDeprecatedMixinEvents(includes) { + if (typeof L === 'undefined' || !L || !L.Mixin) { return; } + + includes = isArray(includes) ? includes : [includes]; + + for (var i = 0; i < includes.length; i++) { + if (includes[i] === L.Mixin.Events) { + console.warn('Deprecated include of L.Mixin.Events: ' + + 'this property will be removed in future releases, ' + + 'please inherit from L.Evented instead.', new Error().stack); + } + } +} + +/* + * @class Evented + * @aka L.Evented + * @inherits Class + * + * A set of methods shared between event-powered classes (like `Map` and `Marker`). Generally, events allow you to execute some function when something happens with an object (e.g. the user clicks on the map, causing the map to fire `'click'` event). + * + * @example + * + * ```js + * map.on('click', function(e) { + * alert(e.latlng); + * } ); + * ``` + * + * Leaflet deals with event listeners by reference, so if you want to add a listener and then remove it, define it as a function: + * + * ```js + * function onClick(e) { ... } + * + * map.on('click', onClick); + * map.off('click', onClick); + * ``` + */ + +var Events = { + /* @method on(type: String, fn: Function, context?: Object): this + * Adds a listener function (`fn`) to a particular event type of the object. You can optionally specify the context of the listener (object the this keyword will point to). You can also pass several space-separated types (e.g. `'click dblclick'`). + * + * @alternative + * @method on(eventMap: Object): this + * Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}` + */ + on: function (types, fn, context) { + + // types can be a map of types/handlers + if (typeof types === 'object') { + for (var type in types) { + // we don't process space-separated events here for performance; + // it's a hot path since Layer uses the on(obj) syntax + this._on(type, types[type], fn); + } + + } else { + // types can be a string of space-separated words + types = splitWords(types); + + for (var i = 0, len = types.length; i < len; i++) { + this._on(types[i], fn, context); + } + } + + return this; + }, + + /* @method off(type: String, fn?: Function, context?: Object): this + * Removes a previously added listener function. If no function is specified, it will remove all the listeners of that particular event from the object. Note that if you passed a custom context to `on`, you must pass the same context to `off` in order to remove the listener. + * + * @alternative + * @method off(eventMap: Object): this + * Removes a set of type/listener pairs. + * + * @alternative + * @method off: this + * Removes all listeners to all events on the object. This includes implicitly attached events. + */ + off: function (types, fn, context) { + + if (!arguments.length) { + // clear all listeners if called without arguments + delete this._events; + + } else if (typeof types === 'object') { + for (var type in types) { + this._off(type, types[type], fn); + } + + } else { + types = splitWords(types); + + var removeAll = arguments.length === 1; + for (var i = 0, len = types.length; i < len; i++) { + if (removeAll) { + this._off(types[i]); + } else { + this._off(types[i], fn, context); + } + } + } + + return this; + }, + + // attach listener (without syntactic sugar now) + _on: function (type, fn, context) { + if (typeof fn !== 'function') { + console.warn('wrong listener type: ' + typeof fn); + return; + } + this._events = this._events || {}; + + /* get/init listeners for type */ + var typeListeners = this._events[type]; + if (!typeListeners) { + typeListeners = []; + this._events[type] = typeListeners; + } + + if (context === this) { + // Less memory footprint. + context = undefined; + } + var newListener = {fn: fn, ctx: context}, + listeners = typeListeners; + + // check if fn already there + for (var i = 0, len = listeners.length; i < len; i++) { + if (listeners[i].fn === fn && listeners[i].ctx === context) { + return; + } + } + + listeners.push(newListener); + }, + + _off: function (type, fn, context) { + var listeners, + i, + len; + + if (!this._events) { return; } + + listeners = this._events[type]; + + if (!listeners) { + return; + } + + if (arguments.length === 1) { // remove all + if (this._firingCount) { + // Set all removed listeners to noop + // so they are not called if remove happens in fire + for (i = 0, len = listeners.length; i < len; i++) { + listeners[i].fn = falseFn; + } + } + // clear all listeners for a type if function isn't specified + delete this._events[type]; + return; + } + + if (context === this) { + context = undefined; + } + + if (typeof fn !== 'function') { + console.warn('wrong listener type: ' + typeof fn); + return; + } + // find fn and remove it + for (i = 0, len = listeners.length; i < len; i++) { + var l = listeners[i]; + if (l.ctx !== context) { continue; } + if (l.fn === fn) { + if (this._firingCount) { + // set the removed listener to noop so that's not called if remove happens in fire + l.fn = falseFn; + + /* copy array in case events are being fired */ + this._events[type] = listeners = listeners.slice(); + } + listeners.splice(i, 1); + + return; + } + } + console.warn('listener not found'); + }, + + // @method fire(type: String, data?: Object, propagate?: Boolean): this + // Fires an event of the specified type. You can optionally provide a data + // object — the first argument of the listener function will contain its + // properties. The event can optionally be propagated to event parents. + fire: function (type, data, propagate) { + if (!this.listens(type, propagate)) { return this; } + + var event = extend({}, data, { + type: type, + target: this, + sourceTarget: data && data.sourceTarget || this + }); + + if (this._events) { + var listeners = this._events[type]; + + if (listeners) { + this._firingCount = (this._firingCount + 1) || 1; + for (var i = 0, len = listeners.length; i < len; i++) { + var l = listeners[i]; + l.fn.call(l.ctx || this, event); + } + + this._firingCount--; + } + } + + if (propagate) { + // propagate the event to parents (set with addEventParent) + this._propagateEvent(event); + } + + return this; + }, + + // @method listens(type: String, propagate?: Boolean): Boolean + // Returns `true` if a particular event type has any listeners attached to it. + // The verification can optionally be propagated, it will return `true` if parents have the listener attached to it. + listens: function (type, propagate) { + if (typeof type !== 'string') { + console.warn('"string" type argument expected'); + } + var listeners = this._events && this._events[type]; + if (listeners && listeners.length) { return true; } + + if (propagate) { + // also check parents for listeners if event propagates + for (var id in this._eventParents) { + if (this._eventParents[id].listens(type, propagate)) { return true; } + } + } + return false; + }, + + // @method once(…): this + // Behaves as [`on(…)`](#evented-on), except the listener will only get fired once and then removed. + once: function (types, fn, context) { + + if (typeof types === 'object') { + for (var type in types) { + this.once(type, types[type], fn); + } + return this; + } + + var handler = bind(function () { + this + .off(types, fn, context) + .off(types, handler, context); + }, this); + + // add a listener that's executed once and removed after that + return this + .on(types, fn, context) + .on(types, handler, context); + }, + + // @method addEventParent(obj: Evented): this + // Adds an event parent - an `Evented` that will receive propagated events + addEventParent: function (obj) { + this._eventParents = this._eventParents || {}; + this._eventParents[stamp(obj)] = obj; + return this; + }, + + // @method removeEventParent(obj: Evented): this + // Removes an event parent, so it will stop receiving propagated events + removeEventParent: function (obj) { + if (this._eventParents) { + delete this._eventParents[stamp(obj)]; + } + return this; + }, + + _propagateEvent: function (e) { + for (var id in this._eventParents) { + this._eventParents[id].fire(e.type, extend({ + layer: e.target, + propagatedFrom: e.target + }, e), true); + } + } +}; + +// aliases; we should ditch those eventually + +// @method addEventListener(…): this +// Alias to [`on(…)`](#evented-on) +Events.addEventListener = Events.on; + +// @method removeEventListener(…): this +// Alias to [`off(…)`](#evented-off) + +// @method clearAllEventListeners(…): this +// Alias to [`off()`](#evented-off) +Events.removeEventListener = Events.clearAllEventListeners = Events.off; + +// @method addOneTimeEventListener(…): this +// Alias to [`once(…)`](#evented-once) +Events.addOneTimeEventListener = Events.once; + +// @method fireEvent(…): this +// Alias to [`fire(…)`](#evented-fire) +Events.fireEvent = Events.fire; + +// @method hasEventListeners(…): Boolean +// Alias to [`listens(…)`](#evented-listens) +Events.hasEventListeners = Events.listens; + +var Evented = Class.extend(Events); + +/* + * @class Point + * @aka L.Point + * + * Represents a point with `x` and `y` coordinates in pixels. + * + * @example + * + * ```js + * var point = L.point(200, 300); + * ``` + * + * All Leaflet methods and options that accept `Point` objects also accept them in a simple Array form (unless noted otherwise), so these lines are equivalent: + * + * ```js + * map.panBy([200, 300]); + * map.panBy(L.point(200, 300)); + * ``` + * + * Note that `Point` does not inherit from Leaflet's `Class` object, + * which means new classes can't inherit from it, and new methods + * can't be added to it with the `include` function. + */ + +function Point(x, y, round) { + // @property x: Number; The `x` coordinate of the point + this.x = (round ? Math.round(x) : x); + // @property y: Number; The `y` coordinate of the point + this.y = (round ? Math.round(y) : y); +} + +var trunc = Math.trunc || function (v) { + return v > 0 ? Math.floor(v) : Math.ceil(v); +}; + +Point.prototype = { + + // @method clone(): Point + // Returns a copy of the current point. + clone: function () { + return new Point(this.x, this.y); + }, + + // @method add(otherPoint: Point): Point + // Returns the result of addition of the current and the given points. + add: function (point) { + // non-destructive, returns a new point + return this.clone()._add(toPoint(point)); + }, + + _add: function (point) { + // destructive, used directly for performance in situations where it's safe to modify existing point + this.x += point.x; + this.y += point.y; + return this; + }, + + // @method subtract(otherPoint: Point): Point + // Returns the result of subtraction of the given point from the current. + subtract: function (point) { + return this.clone()._subtract(toPoint(point)); + }, + + _subtract: function (point) { + this.x -= point.x; + this.y -= point.y; + return this; + }, + + // @method divideBy(num: Number): Point + // Returns the result of division of the current point by the given number. + divideBy: function (num) { + return this.clone()._divideBy(num); + }, + + _divideBy: function (num) { + this.x /= num; + this.y /= num; + return this; + }, + + // @method multiplyBy(num: Number): Point + // Returns the result of multiplication of the current point by the given number. + multiplyBy: function (num) { + return this.clone()._multiplyBy(num); + }, + + _multiplyBy: function (num) { + this.x *= num; + this.y *= num; + return this; + }, + + // @method scaleBy(scale: Point): Point + // Multiply each coordinate of the current point by each coordinate of + // `scale`. In linear algebra terms, multiply the point by the + // [scaling matrix](https://en.wikipedia.org/wiki/Scaling_%28geometry%29#Matrix_representation) + // defined by `scale`. + scaleBy: function (point) { + return new Point(this.x * point.x, this.y * point.y); + }, + + // @method unscaleBy(scale: Point): Point + // Inverse of `scaleBy`. Divide each coordinate of the current point by + // each coordinate of `scale`. + unscaleBy: function (point) { + return new Point(this.x / point.x, this.y / point.y); + }, + + // @method round(): Point + // Returns a copy of the current point with rounded coordinates. + round: function () { + return this.clone()._round(); + }, + + _round: function () { + this.x = Math.round(this.x); + this.y = Math.round(this.y); + return this; + }, + + // @method floor(): Point + // Returns a copy of the current point with floored coordinates (rounded down). + floor: function () { + return this.clone()._floor(); + }, + + _floor: function () { + this.x = Math.floor(this.x); + this.y = Math.floor(this.y); + return this; + }, + + // @method ceil(): Point + // Returns a copy of the current point with ceiled coordinates (rounded up). + ceil: function () { + return this.clone()._ceil(); + }, + + _ceil: function () { + this.x = Math.ceil(this.x); + this.y = Math.ceil(this.y); + return this; + }, + + // @method trunc(): Point + // Returns a copy of the current point with truncated coordinates (rounded towards zero). + trunc: function () { + return this.clone()._trunc(); + }, + + _trunc: function () { + this.x = trunc(this.x); + this.y = trunc(this.y); + return this; + }, + + // @method distanceTo(otherPoint: Point): Number + // Returns the cartesian distance between the current and the given points. + distanceTo: function (point) { + point = toPoint(point); + + var x = point.x - this.x, + y = point.y - this.y; + + return Math.sqrt(x * x + y * y); + }, + + // @method equals(otherPoint: Point): Boolean + // Returns `true` if the given point has the same coordinates. + equals: function (point) { + point = toPoint(point); + + return point.x === this.x && + point.y === this.y; + }, + + // @method contains(otherPoint: Point): Boolean + // Returns `true` if both coordinates of the given point are less than the corresponding current point coordinates (in absolute values). + contains: function (point) { + point = toPoint(point); + + return Math.abs(point.x) <= Math.abs(this.x) && + Math.abs(point.y) <= Math.abs(this.y); + }, + + // @method toString(): String + // Returns a string representation of the point for debugging purposes. + toString: function () { + return 'Point(' + + formatNum(this.x) + ', ' + + formatNum(this.y) + ')'; + } +}; + +// @factory L.point(x: Number, y: Number, round?: Boolean) +// Creates a Point object with the given `x` and `y` coordinates. If optional `round` is set to true, rounds the `x` and `y` values. + +// @alternative +// @factory L.point(coords: Number[]) +// Expects an array of the form `[x, y]` instead. + +// @alternative +// @factory L.point(coords: Object) +// Expects a plain object of the form `{x: Number, y: Number}` instead. +function toPoint(x, y, round) { + if (x instanceof Point) { + return x; + } + if (isArray(x)) { + return new Point(x[0], x[1]); + } + if (x === undefined || x === null) { + return x; + } + if (typeof x === 'object' && 'x' in x && 'y' in x) { + return new Point(x.x, x.y); + } + return new Point(x, y, round); +} + +/* + * @class Bounds + * @aka L.Bounds + * + * Represents a rectangular area in pixel coordinates. + * + * @example + * + * ```js + * var p1 = L.point(10, 10), + * p2 = L.point(40, 60), + * bounds = L.bounds(p1, p2); + * ``` + * + * All Leaflet methods that accept `Bounds` objects also accept them in a simple Array form (unless noted otherwise), so the bounds example above can be passed like this: + * + * ```js + * otherBounds.intersects([[10, 10], [40, 60]]); + * ``` + * + * Note that `Bounds` does not inherit from Leaflet's `Class` object, + * which means new classes can't inherit from it, and new methods + * can't be added to it with the `include` function. + */ + +function Bounds(a, b) { + if (!a) { return; } + + var points = b ? [a, b] : a; + + for (var i = 0, len = points.length; i < len; i++) { + this.extend(points[i]); + } +} + +Bounds.prototype = { + // @method extend(point: Point): this + // Extends the bounds to contain the given point. + extend: function (point) { // (Point) + point = toPoint(point); + + // @property min: Point + // The top left corner of the rectangle. + // @property max: Point + // The bottom right corner of the rectangle. + if (!this.min && !this.max) { + this.min = point.clone(); + this.max = point.clone(); + } else { + this.min.x = Math.min(point.x, this.min.x); + this.max.x = Math.max(point.x, this.max.x); + this.min.y = Math.min(point.y, this.min.y); + this.max.y = Math.max(point.y, this.max.y); + } + return this; + }, + + // @method getCenter(round?: Boolean): Point + // Returns the center point of the bounds. + getCenter: function (round) { + return new Point( + (this.min.x + this.max.x) / 2, + (this.min.y + this.max.y) / 2, round); + }, + + // @method getBottomLeft(): Point + // Returns the bottom-left point of the bounds. + getBottomLeft: function () { + return new Point(this.min.x, this.max.y); + }, + + // @method getTopRight(): Point + // Returns the top-right point of the bounds. + getTopRight: function () { // -> Point + return new Point(this.max.x, this.min.y); + }, + + // @method getTopLeft(): Point + // Returns the top-left point of the bounds (i.e. [`this.min`](#bounds-min)). + getTopLeft: function () { + return this.min; // left, top + }, + + // @method getBottomRight(): Point + // Returns the bottom-right point of the bounds (i.e. [`this.max`](#bounds-max)). + getBottomRight: function () { + return this.max; // right, bottom + }, + + // @method getSize(): Point + // Returns the size of the given bounds + getSize: function () { + return this.max.subtract(this.min); + }, + + // @method contains(otherBounds: Bounds): Boolean + // Returns `true` if the rectangle contains the given one. + // @alternative + // @method contains(point: Point): Boolean + // Returns `true` if the rectangle contains the given point. + contains: function (obj) { + var min, max; + + if (typeof obj[0] === 'number' || obj instanceof Point) { + obj = toPoint(obj); + } else { + obj = toBounds(obj); + } + + if (obj instanceof Bounds) { + min = obj.min; + max = obj.max; + } else { + min = max = obj; + } + + return (min.x >= this.min.x) && + (max.x <= this.max.x) && + (min.y >= this.min.y) && + (max.y <= this.max.y); + }, + + // @method intersects(otherBounds: Bounds): Boolean + // Returns `true` if the rectangle intersects the given bounds. Two bounds + // intersect if they have at least one point in common. + intersects: function (bounds) { // (Bounds) -> Boolean + bounds = toBounds(bounds); + + var min = this.min, + max = this.max, + min2 = bounds.min, + max2 = bounds.max, + xIntersects = (max2.x >= min.x) && (min2.x <= max.x), + yIntersects = (max2.y >= min.y) && (min2.y <= max.y); + + return xIntersects && yIntersects; + }, + + // @method overlaps(otherBounds: Bounds): Boolean + // Returns `true` if the rectangle overlaps the given bounds. Two bounds + // overlap if their intersection is an area. + overlaps: function (bounds) { // (Bounds) -> Boolean + bounds = toBounds(bounds); + + var min = this.min, + max = this.max, + min2 = bounds.min, + max2 = bounds.max, + xOverlaps = (max2.x > min.x) && (min2.x < max.x), + yOverlaps = (max2.y > min.y) && (min2.y < max.y); + + return xOverlaps && yOverlaps; + }, + + isValid: function () { + return !!(this.min && this.max); + } +}; + + +// @factory L.bounds(corner1: Point, corner2: Point) +// Creates a Bounds object from two corners coordinate pairs. +// @alternative +// @factory L.bounds(points: Point[]) +// Creates a Bounds object from the given array of points. +function toBounds(a, b) { + if (!a || a instanceof Bounds) { + return a; + } + return new Bounds(a, b); +} + +/* + * @class LatLngBounds + * @aka L.LatLngBounds + * + * Represents a rectangular geographical area on a map. + * + * @example + * + * ```js + * var corner1 = L.latLng(40.712, -74.227), + * corner2 = L.latLng(40.774, -74.125), + * bounds = L.latLngBounds(corner1, corner2); + * ``` + * + * All Leaflet methods that accept LatLngBounds objects also accept them in a simple Array form (unless noted otherwise), so the bounds example above can be passed like this: + * + * ```js + * map.fitBounds([ + * [40.712, -74.227], + * [40.774, -74.125] + * ]); + * ``` + * + * Caution: if the area crosses the antimeridian (often confused with the International Date Line), you must specify corners _outside_ the [-180, 180] degrees longitude range. + * + * Note that `LatLngBounds` does not inherit from Leaflet's `Class` object, + * which means new classes can't inherit from it, and new methods + * can't be added to it with the `include` function. + */ + +function LatLngBounds(corner1, corner2) { // (LatLng, LatLng) or (LatLng[]) + if (!corner1) { return; } + + var latlngs = corner2 ? [corner1, corner2] : corner1; + + for (var i = 0, len = latlngs.length; i < len; i++) { + this.extend(latlngs[i]); + } +} + +LatLngBounds.prototype = { + + // @method extend(latlng: LatLng): this + // Extend the bounds to contain the given point + + // @alternative + // @method extend(otherBounds: LatLngBounds): this + // Extend the bounds to contain the given bounds + extend: function (obj) { + var sw = this._southWest, + ne = this._northEast, + sw2, ne2; + + if (obj instanceof LatLng) { + sw2 = obj; + ne2 = obj; + + } else if (obj instanceof LatLngBounds) { + sw2 = obj._southWest; + ne2 = obj._northEast; + + if (!sw2 || !ne2) { return this; } + + } else { + return obj ? this.extend(toLatLng(obj) || toLatLngBounds(obj)) : this; + } + + if (!sw && !ne) { + this._southWest = new LatLng(sw2.lat, sw2.lng); + this._northEast = new LatLng(ne2.lat, ne2.lng); + } else { + sw.lat = Math.min(sw2.lat, sw.lat); + sw.lng = Math.min(sw2.lng, sw.lng); + ne.lat = Math.max(ne2.lat, ne.lat); + ne.lng = Math.max(ne2.lng, ne.lng); + } + + return this; + }, + + // @method pad(bufferRatio: Number): LatLngBounds + // Returns bounds created by extending or retracting the current bounds by a given ratio in each direction. + // For example, a ratio of 0.5 extends the bounds by 50% in each direction. + // Negative values will retract the bounds. + pad: function (bufferRatio) { + var sw = this._southWest, + ne = this._northEast, + heightBuffer = Math.abs(sw.lat - ne.lat) * bufferRatio, + widthBuffer = Math.abs(sw.lng - ne.lng) * bufferRatio; + + return new LatLngBounds( + new LatLng(sw.lat - heightBuffer, sw.lng - widthBuffer), + new LatLng(ne.lat + heightBuffer, ne.lng + widthBuffer)); + }, + + // @method getCenter(): LatLng + // Returns the center point of the bounds. + getCenter: function () { + return new LatLng( + (this._southWest.lat + this._northEast.lat) / 2, + (this._southWest.lng + this._northEast.lng) / 2); + }, + + // @method getSouthWest(): LatLng + // Returns the south-west point of the bounds. + getSouthWest: function () { + return this._southWest; + }, + + // @method getNorthEast(): LatLng + // Returns the north-east point of the bounds. + getNorthEast: function () { + return this._northEast; + }, + + // @method getNorthWest(): LatLng + // Returns the north-west point of the bounds. + getNorthWest: function () { + return new LatLng(this.getNorth(), this.getWest()); + }, + + // @method getSouthEast(): LatLng + // Returns the south-east point of the bounds. + getSouthEast: function () { + return new LatLng(this.getSouth(), this.getEast()); + }, + + // @method getWest(): Number + // Returns the west longitude of the bounds + getWest: function () { + return this._southWest.lng; + }, + + // @method getSouth(): Number + // Returns the south latitude of the bounds + getSouth: function () { + return this._southWest.lat; + }, + + // @method getEast(): Number + // Returns the east longitude of the bounds + getEast: function () { + return this._northEast.lng; + }, + + // @method getNorth(): Number + // Returns the north latitude of the bounds + getNorth: function () { + return this._northEast.lat; + }, + + // @method contains(otherBounds: LatLngBounds): Boolean + // Returns `true` if the rectangle contains the given one. + + // @alternative + // @method contains (latlng: LatLng): Boolean + // Returns `true` if the rectangle contains the given point. + contains: function (obj) { // (LatLngBounds) or (LatLng) -> Boolean + if (typeof obj[0] === 'number' || obj instanceof LatLng || 'lat' in obj) { + obj = toLatLng(obj); + } else { + obj = toLatLngBounds(obj); + } + + var sw = this._southWest, + ne = this._northEast, + sw2, ne2; + + if (obj instanceof LatLngBounds) { + sw2 = obj.getSouthWest(); + ne2 = obj.getNorthEast(); + } else { + sw2 = ne2 = obj; + } + + return (sw2.lat >= sw.lat) && (ne2.lat <= ne.lat) && + (sw2.lng >= sw.lng) && (ne2.lng <= ne.lng); + }, + + // @method intersects(otherBounds: LatLngBounds): Boolean + // Returns `true` if the rectangle intersects the given bounds. Two bounds intersect if they have at least one point in common. + intersects: function (bounds) { + bounds = toLatLngBounds(bounds); + + var sw = this._southWest, + ne = this._northEast, + sw2 = bounds.getSouthWest(), + ne2 = bounds.getNorthEast(), + + latIntersects = (ne2.lat >= sw.lat) && (sw2.lat <= ne.lat), + lngIntersects = (ne2.lng >= sw.lng) && (sw2.lng <= ne.lng); + + return latIntersects && lngIntersects; + }, + + // @method overlaps(otherBounds: LatLngBounds): Boolean + // Returns `true` if the rectangle overlaps the given bounds. Two bounds overlap if their intersection is an area. + overlaps: function (bounds) { + bounds = toLatLngBounds(bounds); + + var sw = this._southWest, + ne = this._northEast, + sw2 = bounds.getSouthWest(), + ne2 = bounds.getNorthEast(), + + latOverlaps = (ne2.lat > sw.lat) && (sw2.lat < ne.lat), + lngOverlaps = (ne2.lng > sw.lng) && (sw2.lng < ne.lng); + + return latOverlaps && lngOverlaps; + }, + + // @method toBBoxString(): String + // Returns a string with bounding box coordinates in a 'southwest_lng,southwest_lat,northeast_lng,northeast_lat' format. Useful for sending requests to web services that return geo data. + toBBoxString: function () { + return [this.getWest(), this.getSouth(), this.getEast(), this.getNorth()].join(','); + }, + + // @method equals(otherBounds: LatLngBounds, maxMargin?: Number): Boolean + // Returns `true` if the rectangle is equivalent (within a small margin of error) to the given bounds. The margin of error can be overridden by setting `maxMargin` to a small number. + equals: function (bounds, maxMargin) { + if (!bounds) { return false; } + + bounds = toLatLngBounds(bounds); + + return this._southWest.equals(bounds.getSouthWest(), maxMargin) && + this._northEast.equals(bounds.getNorthEast(), maxMargin); + }, + + // @method isValid(): Boolean + // Returns `true` if the bounds are properly initialized. + isValid: function () { + return !!(this._southWest && this._northEast); + } +}; + +// TODO International date line? + +// @factory L.latLngBounds(corner1: LatLng, corner2: LatLng) +// Creates a `LatLngBounds` object by defining two diagonally opposite corners of the rectangle. + +// @alternative +// @factory L.latLngBounds(latlngs: LatLng[]) +// Creates a `LatLngBounds` object defined by the geographical points it contains. Very useful for zooming the map to fit a particular set of locations with [`fitBounds`](#map-fitbounds). +function toLatLngBounds(a, b) { + if (a instanceof LatLngBounds) { + return a; + } + return new LatLngBounds(a, b); +} + +/* @class LatLng + * @aka L.LatLng + * + * Represents a geographical point with a certain latitude and longitude. + * + * @example + * + * ``` + * var latlng = L.latLng(50.5, 30.5); + * ``` + * + * All Leaflet methods that accept LatLng objects also accept them in a simple Array form and simple object form (unless noted otherwise), so these lines are equivalent: + * + * ``` + * map.panTo([50, 30]); + * map.panTo({lon: 30, lat: 50}); + * map.panTo({lat: 50, lng: 30}); + * map.panTo(L.latLng(50, 30)); + * ``` + * + * Note that `LatLng` does not inherit from Leaflet's `Class` object, + * which means new classes can't inherit from it, and new methods + * can't be added to it with the `include` function. + */ + +function LatLng(lat, lng, alt) { + if (isNaN(lat) || isNaN(lng)) { + throw new Error('Invalid LatLng object: (' + lat + ', ' + lng + ')'); + } + + // @property lat: Number + // Latitude in degrees + this.lat = +lat; + + // @property lng: Number + // Longitude in degrees + this.lng = +lng; + + // @property alt: Number + // Altitude in meters (optional) + if (alt !== undefined) { + this.alt = +alt; + } +} + +LatLng.prototype = { + // @method equals(otherLatLng: LatLng, maxMargin?: Number): Boolean + // Returns `true` if the given `LatLng` point is at the same position (within a small margin of error). The margin of error can be overridden by setting `maxMargin` to a small number. + equals: function (obj, maxMargin) { + if (!obj) { return false; } + + obj = toLatLng(obj); + + var margin = Math.max( + Math.abs(this.lat - obj.lat), + Math.abs(this.lng - obj.lng)); + + return margin <= (maxMargin === undefined ? 1.0E-9 : maxMargin); + }, + + // @method toString(): String + // Returns a string representation of the point (for debugging purposes). + toString: function (precision) { + return 'LatLng(' + + formatNum(this.lat, precision) + ', ' + + formatNum(this.lng, precision) + ')'; + }, + + // @method distanceTo(otherLatLng: LatLng): Number + // Returns the distance (in meters) to the given `LatLng` calculated using the [Spherical Law of Cosines](https://en.wikipedia.org/wiki/Spherical_law_of_cosines). + distanceTo: function (other) { + return Earth.distance(this, toLatLng(other)); + }, + + // @method wrap(): LatLng + // Returns a new `LatLng` object with the longitude wrapped so it's always between -180 and +180 degrees. + wrap: function () { + return Earth.wrapLatLng(this); + }, + + // @method toBounds(sizeInMeters: Number): LatLngBounds + // Returns a new `LatLngBounds` object in which each boundary is `sizeInMeters/2` meters apart from the `LatLng`. + toBounds: function (sizeInMeters) { + var latAccuracy = 180 * sizeInMeters / 40075017, + lngAccuracy = latAccuracy / Math.cos((Math.PI / 180) * this.lat); + + return toLatLngBounds( + [this.lat - latAccuracy, this.lng - lngAccuracy], + [this.lat + latAccuracy, this.lng + lngAccuracy]); + }, + + clone: function () { + return new LatLng(this.lat, this.lng, this.alt); + } +}; + + + +// @factory L.latLng(latitude: Number, longitude: Number, altitude?: Number): LatLng +// Creates an object representing a geographical point with the given latitude and longitude (and optionally altitude). + +// @alternative +// @factory L.latLng(coords: Array): LatLng +// Expects an array of the form `[Number, Number]` or `[Number, Number, Number]` instead. + +// @alternative +// @factory L.latLng(coords: Object): LatLng +// Expects an plain object of the form `{lat: Number, lng: Number}` or `{lat: Number, lng: Number, alt: Number}` instead. + +function toLatLng(a, b, c) { + if (a instanceof LatLng) { + return a; + } + if (isArray(a) && typeof a[0] !== 'object') { + if (a.length === 3) { + return new LatLng(a[0], a[1], a[2]); + } + if (a.length === 2) { + return new LatLng(a[0], a[1]); + } + return null; + } + if (a === undefined || a === null) { + return a; + } + if (typeof a === 'object' && 'lat' in a) { + return new LatLng(a.lat, 'lng' in a ? a.lng : a.lon, a.alt); + } + if (b === undefined) { + return null; + } + return new LatLng(a, b, c); +} + +/* + * @namespace CRS + * @crs L.CRS.Base + * Object that defines coordinate reference systems for projecting + * geographical points into pixel (screen) coordinates and back (and to + * coordinates in other units for [WMS](https://en.wikipedia.org/wiki/Web_Map_Service) services). See + * [spatial reference system](https://en.wikipedia.org/wiki/Spatial_reference_system). + * + * Leaflet defines the most usual CRSs by default. If you want to use a + * CRS not defined by default, take a look at the + * [Proj4Leaflet](https://github.com/kartena/Proj4Leaflet) plugin. + * + * Note that the CRS instances do not inherit from Leaflet's `Class` object, + * and can't be instantiated. Also, new classes can't inherit from them, + * and methods can't be added to them with the `include` function. + */ + +var CRS = { + // @method latLngToPoint(latlng: LatLng, zoom: Number): Point + // Projects geographical coordinates into pixel coordinates for a given zoom. + latLngToPoint: function (latlng, zoom) { + var projectedPoint = this.projection.project(latlng), + scale = this.scale(zoom); + + return this.transformation._transform(projectedPoint, scale); + }, + + // @method pointToLatLng(point: Point, zoom: Number): LatLng + // The inverse of `latLngToPoint`. Projects pixel coordinates on a given + // zoom into geographical coordinates. + pointToLatLng: function (point, zoom) { + var scale = this.scale(zoom), + untransformedPoint = this.transformation.untransform(point, scale); + + return this.projection.unproject(untransformedPoint); + }, + + // @method project(latlng: LatLng): Point + // Projects geographical coordinates into coordinates in units accepted for + // this CRS (e.g. meters for EPSG:3857, for passing it to WMS services). + project: function (latlng) { + return this.projection.project(latlng); + }, + + // @method unproject(point: Point): LatLng + // Given a projected coordinate returns the corresponding LatLng. + // The inverse of `project`. + unproject: function (point) { + return this.projection.unproject(point); + }, + + // @method scale(zoom: Number): Number + // Returns the scale used when transforming projected coordinates into + // pixel coordinates for a particular zoom. For example, it returns + // `256 * 2^zoom` for Mercator-based CRS. + scale: function (zoom) { + return 256 * Math.pow(2, zoom); + }, + + // @method zoom(scale: Number): Number + // Inverse of `scale()`, returns the zoom level corresponding to a scale + // factor of `scale`. + zoom: function (scale) { + return Math.log(scale / 256) / Math.LN2; + }, + + // @method getProjectedBounds(zoom: Number): Bounds + // Returns the projection's bounds scaled and transformed for the provided `zoom`. + getProjectedBounds: function (zoom) { + if (this.infinite) { return null; } + + var b = this.projection.bounds, + s = this.scale(zoom), + min = this.transformation.transform(b.min, s), + max = this.transformation.transform(b.max, s); + + return new Bounds(min, max); + }, + + // @method distance(latlng1: LatLng, latlng2: LatLng): Number + // Returns the distance between two geographical coordinates. + + // @property code: String + // Standard code name of the CRS passed into WMS services (e.g. `'EPSG:3857'`) + // + // @property wrapLng: Number[] + // An array of two numbers defining whether the longitude (horizontal) coordinate + // axis wraps around a given range and how. Defaults to `[-180, 180]` in most + // geographical CRSs. If `undefined`, the longitude axis does not wrap around. + // + // @property wrapLat: Number[] + // Like `wrapLng`, but for the latitude (vertical) axis. + + // wrapLng: [min, max], + // wrapLat: [min, max], + + // @property infinite: Boolean + // If true, the coordinate space will be unbounded (infinite in both axes) + infinite: false, + + // @method wrapLatLng(latlng: LatLng): LatLng + // Returns a `LatLng` where lat and lng has been wrapped according to the + // CRS's `wrapLat` and `wrapLng` properties, if they are outside the CRS's bounds. + wrapLatLng: function (latlng) { + var lng = this.wrapLng ? wrapNum(latlng.lng, this.wrapLng, true) : latlng.lng, + lat = this.wrapLat ? wrapNum(latlng.lat, this.wrapLat, true) : latlng.lat, + alt = latlng.alt; + + return new LatLng(lat, lng, alt); + }, + + // @method wrapLatLngBounds(bounds: LatLngBounds): LatLngBounds + // Returns a `LatLngBounds` with the same size as the given one, ensuring + // that its center is within the CRS's bounds. + // Only accepts actual `L.LatLngBounds` instances, not arrays. + wrapLatLngBounds: function (bounds) { + var center = bounds.getCenter(), + newCenter = this.wrapLatLng(center), + latShift = center.lat - newCenter.lat, + lngShift = center.lng - newCenter.lng; + + if (latShift === 0 && lngShift === 0) { + return bounds; + } + + var sw = bounds.getSouthWest(), + ne = bounds.getNorthEast(), + newSw = new LatLng(sw.lat - latShift, sw.lng - lngShift), + newNe = new LatLng(ne.lat - latShift, ne.lng - lngShift); + + return new LatLngBounds(newSw, newNe); + } +}; + +/* + * @namespace CRS + * @crs L.CRS.Earth + * + * Serves as the base for CRS that are global such that they cover the earth. + * Can only be used as the base for other CRS and cannot be used directly, + * since it does not have a `code`, `projection` or `transformation`. `distance()` returns + * meters. + */ + +var Earth = extend({}, CRS, { + wrapLng: [-180, 180], + + // Mean Earth Radius, as recommended for use by + // the International Union of Geodesy and Geophysics, + // see https://rosettacode.org/wiki/Haversine_formula + R: 6371000, + + // distance between two geographical points using spherical law of cosines approximation + distance: function (latlng1, latlng2) { + var rad = Math.PI / 180, + lat1 = latlng1.lat * rad, + lat2 = latlng2.lat * rad, + sinDLat = Math.sin((latlng2.lat - latlng1.lat) * rad / 2), + sinDLon = Math.sin((latlng2.lng - latlng1.lng) * rad / 2), + a = sinDLat * sinDLat + Math.cos(lat1) * Math.cos(lat2) * sinDLon * sinDLon, + c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); + return this.R * c; + } +}); + +/* + * @namespace Projection + * @projection L.Projection.SphericalMercator + * + * Spherical Mercator projection — the most common projection for online maps, + * used by almost all free and commercial tile providers. Assumes that Earth is + * a sphere. Used by the `EPSG:3857` CRS. + */ + +var earthRadius = 6378137; + +var SphericalMercator = { + + R: earthRadius, + MAX_LATITUDE: 85.0511287798, + + project: function (latlng) { + var d = Math.PI / 180, + max = this.MAX_LATITUDE, + lat = Math.max(Math.min(max, latlng.lat), -max), + sin = Math.sin(lat * d); + + return new Point( + this.R * latlng.lng * d, + this.R * Math.log((1 + sin) / (1 - sin)) / 2); + }, + + unproject: function (point) { + var d = 180 / Math.PI; + + return new LatLng( + (2 * Math.atan(Math.exp(point.y / this.R)) - (Math.PI / 2)) * d, + point.x * d / this.R); + }, + + bounds: (function () { + var d = earthRadius * Math.PI; + return new Bounds([-d, -d], [d, d]); + })() +}; + +/* + * @class Transformation + * @aka L.Transformation + * + * Represents an affine transformation: a set of coefficients `a`, `b`, `c`, `d` + * for transforming a point of a form `(x, y)` into `(a*x + b, c*y + d)` and doing + * the reverse. Used by Leaflet in its projections code. + * + * @example + * + * ```js + * var transformation = L.transformation(2, 5, -1, 10), + * p = L.point(1, 2), + * p2 = transformation.transform(p), // L.point(7, 8) + * p3 = transformation.untransform(p2); // L.point(1, 2) + * ``` + */ + + +// factory new L.Transformation(a: Number, b: Number, c: Number, d: Number) +// Creates a `Transformation` object with the given coefficients. +function Transformation(a, b, c, d) { + if (isArray(a)) { + // use array properties + this._a = a[0]; + this._b = a[1]; + this._c = a[2]; + this._d = a[3]; + return; + } + this._a = a; + this._b = b; + this._c = c; + this._d = d; +} + +Transformation.prototype = { + // @method transform(point: Point, scale?: Number): Point + // Returns a transformed point, optionally multiplied by the given scale. + // Only accepts actual `L.Point` instances, not arrays. + transform: function (point, scale) { // (Point, Number) -> Point + return this._transform(point.clone(), scale); + }, + + // destructive transform (faster) + _transform: function (point, scale) { + scale = scale || 1; + point.x = scale * (this._a * point.x + this._b); + point.y = scale * (this._c * point.y + this._d); + return point; + }, + + // @method untransform(point: Point, scale?: Number): Point + // Returns the reverse transformation of the given point, optionally divided + // by the given scale. Only accepts actual `L.Point` instances, not arrays. + untransform: function (point, scale) { + scale = scale || 1; + return new Point( + (point.x / scale - this._b) / this._a, + (point.y / scale - this._d) / this._c); + } +}; + +// factory L.transformation(a: Number, b: Number, c: Number, d: Number) + +// @factory L.transformation(a: Number, b: Number, c: Number, d: Number) +// Instantiates a Transformation object with the given coefficients. + +// @alternative +// @factory L.transformation(coefficients: Array): Transformation +// Expects an coefficients array of the form +// `[a: Number, b: Number, c: Number, d: Number]`. + +function toTransformation(a, b, c, d) { + return new Transformation(a, b, c, d); +} + +/* + * @namespace CRS + * @crs L.CRS.EPSG3857 + * + * The most common CRS for online maps, used by almost all free and commercial + * tile providers. Uses Spherical Mercator projection. Set in by default in + * Map's `crs` option. + */ + +var EPSG3857 = extend({}, Earth, { + code: 'EPSG:3857', + projection: SphericalMercator, + + transformation: (function () { + var scale = 0.5 / (Math.PI * SphericalMercator.R); + return toTransformation(scale, 0.5, -scale, 0.5); + }()) +}); + +var EPSG900913 = extend({}, EPSG3857, { + code: 'EPSG:900913' +}); + +// @namespace SVG; @section +// There are several static functions which can be called without instantiating L.SVG: + +// @function create(name: String): SVGElement +// Returns a instance of [SVGElement](https://developer.mozilla.org/docs/Web/API/SVGElement), +// corresponding to the class name passed. For example, using 'line' will return +// an instance of [SVGLineElement](https://developer.mozilla.org/docs/Web/API/SVGLineElement). +function svgCreate(name) { + return document.createElementNS('http://www.w3.org/2000/svg', name); +} + +// @function pointsToPath(rings: Point[], closed: Boolean): String +// Generates a SVG path string for multiple rings, with each ring turning +// into "M..L..L.." instructions +function pointsToPath(rings, closed) { + var str = '', + i, j, len, len2, points, p; + + for (i = 0, len = rings.length; i < len; i++) { + points = rings[i]; + + for (j = 0, len2 = points.length; j < len2; j++) { + p = points[j]; + str += (j ? 'L' : 'M') + p.x + ' ' + p.y; + } + + // closes the ring for polygons; "x" is VML syntax + str += closed ? (Browser.svg ? 'z' : 'x') : ''; + } + + // SVG complains about empty path strings + return str || 'M0 0'; +} + +/* + * @namespace Browser + * @aka L.Browser + * + * A namespace with static properties for browser/feature detection used by Leaflet internally. + * + * @example + * + * ```js + * if (L.Browser.ielt9) { + * alert('Upgrade your browser, dude!'); + * } + * ``` + */ + +var style = document.documentElement.style; + +// @property ie: Boolean; `true` for all Internet Explorer versions (not Edge). +var ie = 'ActiveXObject' in window; + +// @property ielt9: Boolean; `true` for Internet Explorer versions less than 9. +var ielt9 = ie && !document.addEventListener; + +// @property edge: Boolean; `true` for the Edge web browser. +var edge = 'msLaunchUri' in navigator && !('documentMode' in document); + +// @property webkit: Boolean; +// `true` for webkit-based browsers like Chrome and Safari (including mobile versions). +var webkit = userAgentContains('webkit'); + +// @property android: Boolean +// **Deprecated.** `true` for any browser running on an Android platform. +var android = userAgentContains('android'); + +// @property android23: Boolean; **Deprecated.** `true` for browsers running on Android 2 or Android 3. +var android23 = userAgentContains('android 2') || userAgentContains('android 3'); + +/* See https://stackoverflow.com/a/17961266 for details on detecting stock Android */ +var webkitVer = parseInt(/WebKit\/([0-9]+)|$/.exec(navigator.userAgent)[1], 10); // also matches AppleWebKit +// @property androidStock: Boolean; **Deprecated.** `true` for the Android stock browser (i.e. not Chrome) +var androidStock = android && userAgentContains('Google') && webkitVer < 537 && !('AudioNode' in window); + +// @property opera: Boolean; `true` for the Opera browser +var opera = !!window.opera; + +// @property chrome: Boolean; `true` for the Chrome browser. +var chrome = !edge && userAgentContains('chrome'); + +// @property gecko: Boolean; `true` for gecko-based browsers like Firefox. +var gecko = userAgentContains('gecko') && !webkit && !opera && !ie; + +// @property safari: Boolean; `true` for the Safari browser. +var safari = !chrome && userAgentContains('safari'); + +var phantom = userAgentContains('phantom'); + +// @property opera12: Boolean +// `true` for the Opera browser supporting CSS transforms (version 12 or later). +var opera12 = 'OTransition' in style; + +// @property win: Boolean; `true` when the browser is running in a Windows platform +var win = navigator.platform.indexOf('Win') === 0; + +// @property ie3d: Boolean; `true` for all Internet Explorer versions supporting CSS transforms. +var ie3d = ie && ('transition' in style); + +// @property webkit3d: Boolean; `true` for webkit-based browsers supporting CSS transforms. +var webkit3d = ('WebKitCSSMatrix' in window) && ('m11' in new window.WebKitCSSMatrix()) && !android23; + +// @property gecko3d: Boolean; `true` for gecko-based browsers supporting CSS transforms. +var gecko3d = 'MozPerspective' in style; + +// @property any3d: Boolean +// `true` for all browsers supporting CSS transforms. +var any3d = !window.L_DISABLE_3D && (ie3d || webkit3d || gecko3d) && !opera12 && !phantom; + +// @property mobile: Boolean; `true` for all browsers running in a mobile device. +var mobile = typeof orientation !== 'undefined' || userAgentContains('mobile'); + +// @property mobileWebkit: Boolean; `true` for all webkit-based browsers in a mobile device. +var mobileWebkit = mobile && webkit; + +// @property mobileWebkit3d: Boolean +// `true` for all webkit-based browsers in a mobile device supporting CSS transforms. +var mobileWebkit3d = mobile && webkit3d; + +// @property msPointer: Boolean +// `true` for browsers implementing the Microsoft touch events model (notably IE10). +var msPointer = !window.PointerEvent && window.MSPointerEvent; + +// @property pointer: Boolean +// `true` for all browsers supporting [pointer events](https://msdn.microsoft.com/en-us/library/dn433244%28v=vs.85%29.aspx). +var pointer = !!(window.PointerEvent || msPointer); + +// @property touchNative: Boolean +// `true` for all browsers supporting [touch events](https://developer.mozilla.org/docs/Web/API/Touch_events). +// **This does not necessarily mean** that the browser is running in a computer with +// a touchscreen, it only means that the browser is capable of understanding +// touch events. +var touchNative = 'ontouchstart' in window || !!window.TouchEvent; + +// @property touch: Boolean +// `true` for all browsers supporting either [touch](#browser-touch) or [pointer](#browser-pointer) events. +// Note: pointer events will be preferred (if available), and processed for all `touch*` listeners. +var touch = !window.L_NO_TOUCH && (touchNative || pointer); + +// @property mobileOpera: Boolean; `true` for the Opera browser in a mobile device. +var mobileOpera = mobile && opera; + +// @property mobileGecko: Boolean +// `true` for gecko-based browsers running in a mobile device. +var mobileGecko = mobile && gecko; + +// @property retina: Boolean +// `true` for browsers on a high-resolution "retina" screen or on any screen when browser's display zoom is more than 100%. +var retina = (window.devicePixelRatio || (window.screen.deviceXDPI / window.screen.logicalXDPI)) > 1; + +// @property passiveEvents: Boolean +// `true` for browsers that support passive events. +var passiveEvents = (function () { + var supportsPassiveOption = false; + try { + var opts = Object.defineProperty({}, 'passive', { + get: function () { // eslint-disable-line getter-return + supportsPassiveOption = true; + } + }); + window.addEventListener('testPassiveEventSupport', falseFn, opts); + window.removeEventListener('testPassiveEventSupport', falseFn, opts); + } catch (e) { + // Errors can safely be ignored since this is only a browser support test. + } + return supportsPassiveOption; +}()); + +// @property canvas: Boolean +// `true` when the browser supports [``](https://developer.mozilla.org/docs/Web/API/Canvas_API). +var canvas$1 = (function () { + return !!document.createElement('canvas').getContext; +}()); + +// @property svg: Boolean +// `true` when the browser supports [SVG](https://developer.mozilla.org/docs/Web/SVG). +var svg$1 = !!(document.createElementNS && svgCreate('svg').createSVGRect); + +var inlineSvg = !!svg$1 && (function () { + var div = document.createElement('div'); + div.innerHTML = ''; + return (div.firstChild && div.firstChild.namespaceURI) === 'http://www.w3.org/2000/svg'; +})(); + +// @property vml: Boolean +// `true` if the browser supports [VML](https://en.wikipedia.org/wiki/Vector_Markup_Language). +var vml = !svg$1 && (function () { + try { + var div = document.createElement('div'); + div.innerHTML = ''; + + var shape = div.firstChild; + shape.style.behavior = 'url(#default#VML)'; + + return shape && (typeof shape.adj === 'object'); + + } catch (e) { + return false; + } +}()); + +function userAgentContains(str) { + return navigator.userAgent.toLowerCase().indexOf(str) >= 0; +} + + +var Browser = { + ie: ie, + ielt9: ielt9, + edge: edge, + webkit: webkit, + android: android, + android23: android23, + androidStock: androidStock, + opera: opera, + chrome: chrome, + gecko: gecko, + safari: safari, + phantom: phantom, + opera12: opera12, + win: win, + ie3d: ie3d, + webkit3d: webkit3d, + gecko3d: gecko3d, + any3d: any3d, + mobile: mobile, + mobileWebkit: mobileWebkit, + mobileWebkit3d: mobileWebkit3d, + msPointer: msPointer, + pointer: pointer, + touch: touch, + touchNative: touchNative, + mobileOpera: mobileOpera, + mobileGecko: mobileGecko, + retina: retina, + passiveEvents: passiveEvents, + canvas: canvas$1, + svg: svg$1, + vml: vml, + inlineSvg: inlineSvg +}; + +/* + * Extends L.DomEvent to provide touch support for Internet Explorer and Windows-based devices. + */ + +var POINTER_DOWN = Browser.msPointer ? 'MSPointerDown' : 'pointerdown'; +var POINTER_MOVE = Browser.msPointer ? 'MSPointerMove' : 'pointermove'; +var POINTER_UP = Browser.msPointer ? 'MSPointerUp' : 'pointerup'; +var POINTER_CANCEL = Browser.msPointer ? 'MSPointerCancel' : 'pointercancel'; +var pEvent = { + touchstart : POINTER_DOWN, + touchmove : POINTER_MOVE, + touchend : POINTER_UP, + touchcancel : POINTER_CANCEL +}; +var handle = { + touchstart : _onPointerStart, + touchmove : _handlePointer, + touchend : _handlePointer, + touchcancel : _handlePointer +}; +var _pointers = {}; +var _pointerDocListener = false; + +// Provides a touch events wrapper for (ms)pointer events. +// ref https://www.w3.org/TR/pointerevents/ https://www.w3.org/Bugs/Public/show_bug.cgi?id=22890 + +function addPointerListener(obj, type, handler) { + if (type === 'touchstart') { + _addPointerDocListener(); + } + if (!handle[type]) { + console.warn('wrong event specified:', type); + return L.Util.falseFn; + } + handler = handle[type].bind(this, handler); + obj.addEventListener(pEvent[type], handler, false); + return handler; +} + +function removePointerListener(obj, type, handler) { + if (!pEvent[type]) { + console.warn('wrong event specified:', type); + return; + } + obj.removeEventListener(pEvent[type], handler, false); +} + +function _globalPointerDown(e) { + _pointers[e.pointerId] = e; +} + +function _globalPointerMove(e) { + if (_pointers[e.pointerId]) { + _pointers[e.pointerId] = e; + } +} + +function _globalPointerUp(e) { + delete _pointers[e.pointerId]; +} + +function _addPointerDocListener() { + // need to keep track of what pointers and how many are active to provide e.touches emulation + if (!_pointerDocListener) { + // we listen document as any drags that end by moving the touch off the screen get fired there + document.addEventListener(POINTER_DOWN, _globalPointerDown, true); + document.addEventListener(POINTER_MOVE, _globalPointerMove, true); + document.addEventListener(POINTER_UP, _globalPointerUp, true); + document.addEventListener(POINTER_CANCEL, _globalPointerUp, true); + + _pointerDocListener = true; + } +} + +function _handlePointer(handler, e) { + if (e.pointerType === (e.MSPOINTER_TYPE_MOUSE || 'mouse')) { return; } + + e.touches = []; + for (var i in _pointers) { + e.touches.push(_pointers[i]); + } + e.changedTouches = [e]; + + handler(e); +} + +function _onPointerStart(handler, e) { + // IE10 specific: MsTouch needs preventDefault. See #2000 + if (e.MSPOINTER_TYPE_TOUCH && e.pointerType === e.MSPOINTER_TYPE_TOUCH) { + preventDefault(e); + } + _handlePointer(handler, e); +} + +/* + * Extends the event handling code with double tap support for mobile browsers. + * + * Note: currently most browsers fire native dblclick, with only a few exceptions + * (see https://github.com/Leaflet/Leaflet/issues/7012#issuecomment-595087386) + */ + +function makeDblclick(event) { + // in modern browsers `type` cannot be just overridden: + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Getter_only + var newEvent = {}, + prop, i; + for (i in event) { + prop = event[i]; + newEvent[i] = prop && prop.bind ? prop.bind(event) : prop; + } + event = newEvent; + newEvent.type = 'dblclick'; + newEvent.detail = 2; + newEvent.isTrusted = false; + newEvent._simulated = true; // for debug purposes + return newEvent; +} + +var delay = 200; +function addDoubleTapListener(obj, handler) { + // Most browsers handle double tap natively + obj.addEventListener('dblclick', handler); + + // On some platforms the browser doesn't fire native dblclicks for touch events. + // It seems that in all such cases `detail` property of `click` event is always `1`. + // So here we rely on that fact to avoid excessive 'dblclick' simulation when not needed. + var last = 0, + detail; + function simDblclick(e) { + if (e.detail !== 1) { + detail = e.detail; // keep in sync to avoid false dblclick in some cases + return; + } + + if (e.pointerType === 'mouse' || + (e.sourceCapabilities && !e.sourceCapabilities.firesTouchEvents)) { + + return; + } + + var now = Date.now(); + if (now - last <= delay) { + detail++; + if (detail === 2) { + handler(makeDblclick(e)); + } + } else { + detail = 1; + } + last = now; + } + + obj.addEventListener('click', simDblclick); + + return { + dblclick: handler, + simDblclick: simDblclick + }; +} + +function removeDoubleTapListener(obj, handlers) { + obj.removeEventListener('dblclick', handlers.dblclick); + obj.removeEventListener('click', handlers.simDblclick); +} + +/* + * @namespace DomUtil + * + * Utility functions to work with the [DOM](https://developer.mozilla.org/docs/Web/API/Document_Object_Model) + * tree, used by Leaflet internally. + * + * Most functions expecting or returning a `HTMLElement` also work for + * SVG elements. The only difference is that classes refer to CSS classes + * in HTML and SVG classes in SVG. + */ + + +// @property TRANSFORM: String +// Vendor-prefixed transform style name (e.g. `'webkitTransform'` for WebKit). +var TRANSFORM = testProp( + ['transform', 'webkitTransform', 'OTransform', 'MozTransform', 'msTransform']); + +// webkitTransition comes first because some browser versions that drop vendor prefix don't do +// the same for the transitionend event, in particular the Android 4.1 stock browser + +// @property TRANSITION: String +// Vendor-prefixed transition style name. +var TRANSITION = testProp( + ['webkitTransition', 'transition', 'OTransition', 'MozTransition', 'msTransition']); + +// @property TRANSITION_END: String +// Vendor-prefixed transitionend event name. +var TRANSITION_END = + TRANSITION === 'webkitTransition' || TRANSITION === 'OTransition' ? TRANSITION + 'End' : 'transitionend'; + + +// @function get(id: String|HTMLElement): HTMLElement +// Returns an element given its DOM id, or returns the element itself +// if it was passed directly. +function get(id) { + return typeof id === 'string' ? document.getElementById(id) : id; +} + +// @function getStyle(el: HTMLElement, styleAttrib: String): String +// Returns the value for a certain style attribute on an element, +// including computed values or values set through CSS. +function getStyle(el, style) { + var value = el.style[style] || (el.currentStyle && el.currentStyle[style]); + + if ((!value || value === 'auto') && document.defaultView) { + var css = document.defaultView.getComputedStyle(el, null); + value = css ? css[style] : null; + } + return value === 'auto' ? null : value; +} + +// @function create(tagName: String, className?: String, container?: HTMLElement): HTMLElement +// Creates an HTML element with `tagName`, sets its class to `className`, and optionally appends it to `container` element. +function create$1(tagName, className, container) { + var el = document.createElement(tagName); + el.className = className || ''; + + if (container) { + container.appendChild(el); + } + return el; +} + +// @function remove(el: HTMLElement) +// Removes `el` from its parent element +function remove(el) { + var parent = el.parentNode; + if (parent) { + parent.removeChild(el); + } +} + +// @function empty(el: HTMLElement) +// Removes all of `el`'s children elements from `el` +function empty(el) { + while (el.firstChild) { + el.removeChild(el.firstChild); + } +} + +// @function toFront(el: HTMLElement) +// Makes `el` the last child of its parent, so it renders in front of the other children. +function toFront(el) { + var parent = el.parentNode; + if (parent && parent.lastChild !== el) { + parent.appendChild(el); + } +} + +// @function toBack(el: HTMLElement) +// Makes `el` the first child of its parent, so it renders behind the other children. +function toBack(el) { + var parent = el.parentNode; + if (parent && parent.firstChild !== el) { + parent.insertBefore(el, parent.firstChild); + } +} + +// @function hasClass(el: HTMLElement, name: String): Boolean +// Returns `true` if the element's class attribute contains `name`. +function hasClass(el, name) { + if (el.classList !== undefined) { + return el.classList.contains(name); + } + var className = getClass(el); + return className.length > 0 && new RegExp('(^|\\s)' + name + '(\\s|$)').test(className); +} + +// @function addClass(el: HTMLElement, name: String) +// Adds `name` to the element's class attribute. +function addClass(el, name) { + if (el.classList !== undefined) { + var classes = splitWords(name); + for (var i = 0, len = classes.length; i < len; i++) { + el.classList.add(classes[i]); + } + } else if (!hasClass(el, name)) { + var className = getClass(el); + setClass(el, (className ? className + ' ' : '') + name); + } +} + +// @function removeClass(el: HTMLElement, name: String) +// Removes `name` from the element's class attribute. +function removeClass(el, name) { + if (el.classList !== undefined) { + el.classList.remove(name); + } else { + setClass(el, trim((' ' + getClass(el) + ' ').replace(' ' + name + ' ', ' '))); + } +} + +// @function setClass(el: HTMLElement, name: String) +// Sets the element's class. +function setClass(el, name) { + if (el.className.baseVal === undefined) { + el.className = name; + } else { + // in case of SVG element + el.className.baseVal = name; + } +} + +// @function getClass(el: HTMLElement): String +// Returns the element's class. +function getClass(el) { + // Check if the element is an SVGElementInstance and use the correspondingElement instead + // (Required for linked SVG elements in IE11.) + if (el.correspondingElement) { + el = el.correspondingElement; + } + return el.className.baseVal === undefined ? el.className : el.className.baseVal; +} + +// @function setOpacity(el: HTMLElement, opacity: Number) +// Set the opacity of an element (including old IE support). +// `opacity` must be a number from `0` to `1`. +function setOpacity(el, value) { + if ('opacity' in el.style) { + el.style.opacity = value; + } else if ('filter' in el.style) { + _setOpacityIE(el, value); + } +} + +function _setOpacityIE(el, value) { + var filter = false, + filterName = 'DXImageTransform.Microsoft.Alpha'; + + // filters collection throws an error if we try to retrieve a filter that doesn't exist + try { + filter = el.filters.item(filterName); + } catch (e) { + // don't set opacity to 1 if we haven't already set an opacity, + // it isn't needed and breaks transparent pngs. + if (value === 1) { return; } + } + + value = Math.round(value * 100); + + if (filter) { + filter.Enabled = (value !== 100); + filter.Opacity = value; + } else { + el.style.filter += ' progid:' + filterName + '(opacity=' + value + ')'; + } +} + +// @function testProp(props: String[]): String|false +// Goes through the array of style names and returns the first name +// that is a valid style name for an element. If no such name is found, +// it returns false. Useful for vendor-prefixed styles like `transform`. +function testProp(props) { + var style = document.documentElement.style; + + for (var i = 0; i < props.length; i++) { + if (props[i] in style) { + return props[i]; + } + } + return false; +} + +// @function setTransform(el: HTMLElement, offset: Point, scale?: Number) +// Resets the 3D CSS transform of `el` so it is translated by `offset` pixels +// and optionally scaled by `scale`. Does not have an effect if the +// browser doesn't support 3D CSS transforms. +function setTransform(el, offset, scale) { + var pos = offset || new Point(0, 0); + + el.style[TRANSFORM] = + (Browser.ie3d ? + 'translate(' + pos.x + 'px,' + pos.y + 'px)' : + 'translate3d(' + pos.x + 'px,' + pos.y + 'px,0)') + + (scale ? ' scale(' + scale + ')' : ''); +} + +// @function setPosition(el: HTMLElement, position: Point) +// Sets the position of `el` to coordinates specified by `position`, +// using CSS translate or top/left positioning depending on the browser +// (used by Leaflet internally to position its layers). +function setPosition(el, point) { + + /*eslint-disable */ + el._leaflet_pos = point; + /* eslint-enable */ + + if (Browser.any3d) { + setTransform(el, point); + } else { + el.style.left = point.x + 'px'; + el.style.top = point.y + 'px'; + } +} + +// @function getPosition(el: HTMLElement): Point +// Returns the coordinates of an element previously positioned with setPosition. +function getPosition(el) { + // this method is only used for elements previously positioned using setPosition, + // so it's safe to cache the position for performance + + return el._leaflet_pos || new Point(0, 0); +} + +// @function disableTextSelection() +// Prevents the user from generating `selectstart` DOM events, usually generated +// when the user drags the mouse through a page with text. Used internally +// by Leaflet to override the behaviour of any click-and-drag interaction on +// the map. Affects drag interactions on the whole document. + +// @function enableTextSelection() +// Cancels the effects of a previous [`L.DomUtil.disableTextSelection`](#domutil-disabletextselection). +var disableTextSelection; +var enableTextSelection; +var _userSelect; +if ('onselectstart' in document) { + disableTextSelection = function () { + on(window, 'selectstart', preventDefault); + }; + enableTextSelection = function () { + off(window, 'selectstart', preventDefault); + }; +} else { + var userSelectProperty = testProp( + ['userSelect', 'WebkitUserSelect', 'OUserSelect', 'MozUserSelect', 'msUserSelect']); + + disableTextSelection = function () { + if (userSelectProperty) { + var style = document.documentElement.style; + _userSelect = style[userSelectProperty]; + style[userSelectProperty] = 'none'; + } + }; + enableTextSelection = function () { + if (userSelectProperty) { + document.documentElement.style[userSelectProperty] = _userSelect; + _userSelect = undefined; + } + }; +} + +// @function disableImageDrag() +// As [`L.DomUtil.disableTextSelection`](#domutil-disabletextselection), but +// for `dragstart` DOM events, usually generated when the user drags an image. +function disableImageDrag() { + on(window, 'dragstart', preventDefault); +} + +// @function enableImageDrag() +// Cancels the effects of a previous [`L.DomUtil.disableImageDrag`](#domutil-disabletextselection). +function enableImageDrag() { + off(window, 'dragstart', preventDefault); +} + +var _outlineElement, _outlineStyle; +// @function preventOutline(el: HTMLElement) +// Makes the [outline](https://developer.mozilla.org/docs/Web/CSS/outline) +// of the element `el` invisible. Used internally by Leaflet to prevent +// focusable elements from displaying an outline when the user performs a +// drag interaction on them. +function preventOutline(element) { + while (element.tabIndex === -1) { + element = element.parentNode; + } + if (!element.style) { return; } + restoreOutline(); + _outlineElement = element; + _outlineStyle = element.style.outline; + element.style.outline = 'none'; + on(window, 'keydown', restoreOutline); +} + +// @function restoreOutline() +// Cancels the effects of a previous [`L.DomUtil.preventOutline`](). +function restoreOutline() { + if (!_outlineElement) { return; } + _outlineElement.style.outline = _outlineStyle; + _outlineElement = undefined; + _outlineStyle = undefined; + off(window, 'keydown', restoreOutline); +} + +// @function getSizedParentNode(el: HTMLElement): HTMLElement +// Finds the closest parent node which size (width and height) is not null. +function getSizedParentNode(element) { + do { + element = element.parentNode; + } while ((!element.offsetWidth || !element.offsetHeight) && element !== document.body); + return element; +} + +// @function getScale(el: HTMLElement): Object +// Computes the CSS scale currently applied on the element. +// Returns an object with `x` and `y` members as horizontal and vertical scales respectively, +// and `boundingClientRect` as the result of [`getBoundingClientRect()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect). +function getScale(element) { + var rect = element.getBoundingClientRect(); // Read-only in old browsers. + + return { + x: rect.width / element.offsetWidth || 1, + y: rect.height / element.offsetHeight || 1, + boundingClientRect: rect + }; +} + +var DomUtil = { + __proto__: null, + TRANSFORM: TRANSFORM, + TRANSITION: TRANSITION, + TRANSITION_END: TRANSITION_END, + get: get, + getStyle: getStyle, + create: create$1, + remove: remove, + empty: empty, + toFront: toFront, + toBack: toBack, + hasClass: hasClass, + addClass: addClass, + removeClass: removeClass, + setClass: setClass, + getClass: getClass, + setOpacity: setOpacity, + testProp: testProp, + setTransform: setTransform, + setPosition: setPosition, + getPosition: getPosition, + get disableTextSelection () { return disableTextSelection; }, + get enableTextSelection () { return enableTextSelection; }, + disableImageDrag: disableImageDrag, + enableImageDrag: enableImageDrag, + preventOutline: preventOutline, + restoreOutline: restoreOutline, + getSizedParentNode: getSizedParentNode, + getScale: getScale +}; + +/* + * @namespace DomEvent + * Utility functions to work with the [DOM events](https://developer.mozilla.org/docs/Web/API/Event), used by Leaflet internally. + */ + +// Inspired by John Resig, Dean Edwards and YUI addEvent implementations. + +// @function on(el: HTMLElement, types: String, fn: Function, context?: Object): this +// Adds a listener function (`fn`) to a particular DOM event type of the +// element `el`. You can optionally specify the context of the listener +// (object the `this` keyword will point to). You can also pass several +// space-separated types (e.g. `'click dblclick'`). + +// @alternative +// @function on(el: HTMLElement, eventMap: Object, context?: Object): this +// Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}` +function on(obj, types, fn, context) { + + if (types && typeof types === 'object') { + for (var type in types) { + addOne(obj, type, types[type], fn); + } + } else { + types = splitWords(types); + + for (var i = 0, len = types.length; i < len; i++) { + addOne(obj, types[i], fn, context); + } + } + + return this; +} + +var eventsKey = '_leaflet_events'; + +// @function off(el: HTMLElement, types: String, fn: Function, context?: Object): this +// Removes a previously added listener function. +// Note that if you passed a custom context to on, you must pass the same +// context to `off` in order to remove the listener. + +// @alternative +// @function off(el: HTMLElement, eventMap: Object, context?: Object): this +// Removes a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}` + +// @alternative +// @function off(el: HTMLElement, types: String): this +// Removes all previously added listeners of given types. + +// @alternative +// @function off(el: HTMLElement): this +// Removes all previously added listeners from given HTMLElement +function off(obj, types, fn, context) { + + if (arguments.length === 1) { + batchRemove(obj); + delete obj[eventsKey]; + + } else if (types && typeof types === 'object') { + for (var type in types) { + removeOne(obj, type, types[type], fn); + } + + } else { + types = splitWords(types); + + if (arguments.length === 2) { + batchRemove(obj, function (type) { + return indexOf(types, type) !== -1; + }); + } else { + for (var i = 0, len = types.length; i < len; i++) { + removeOne(obj, types[i], fn, context); + } + } + } + + return this; +} + +function batchRemove(obj, filterFn) { + for (var id in obj[eventsKey]) { + var type = id.split(/\d/)[0]; + if (!filterFn || filterFn(type)) { + removeOne(obj, type, null, null, id); + } + } +} + +var mouseSubst = { + mouseenter: 'mouseover', + mouseleave: 'mouseout', + wheel: !('onwheel' in window) && 'mousewheel' +}; + +function addOne(obj, type, fn, context) { + var id = type + stamp(fn) + (context ? '_' + stamp(context) : ''); + + if (obj[eventsKey] && obj[eventsKey][id]) { return this; } + + var handler = function (e) { + return fn.call(context || obj, e || window.event); + }; + + var originalHandler = handler; + + if (!Browser.touchNative && Browser.pointer && type.indexOf('touch') === 0) { + // Needs DomEvent.Pointer.js + handler = addPointerListener(obj, type, handler); + + } else if (Browser.touch && (type === 'dblclick')) { + handler = addDoubleTapListener(obj, handler); + + } else if ('addEventListener' in obj) { + + if (type === 'touchstart' || type === 'touchmove' || type === 'wheel' || type === 'mousewheel') { + obj.addEventListener(mouseSubst[type] || type, handler, Browser.passiveEvents ? {passive: false} : false); + + } else if (type === 'mouseenter' || type === 'mouseleave') { + handler = function (e) { + e = e || window.event; + if (isExternalTarget(obj, e)) { + originalHandler(e); + } + }; + obj.addEventListener(mouseSubst[type], handler, false); + + } else { + obj.addEventListener(type, originalHandler, false); + } + + } else { + obj.attachEvent('on' + type, handler); + } + + obj[eventsKey] = obj[eventsKey] || {}; + obj[eventsKey][id] = handler; +} + +function removeOne(obj, type, fn, context, id) { + id = id || type + stamp(fn) + (context ? '_' + stamp(context) : ''); + var handler = obj[eventsKey] && obj[eventsKey][id]; + + if (!handler) { return this; } + + if (!Browser.touchNative && Browser.pointer && type.indexOf('touch') === 0) { + removePointerListener(obj, type, handler); + + } else if (Browser.touch && (type === 'dblclick')) { + removeDoubleTapListener(obj, handler); + + } else if ('removeEventListener' in obj) { + + obj.removeEventListener(mouseSubst[type] || type, handler, false); + + } else { + obj.detachEvent('on' + type, handler); + } + + obj[eventsKey][id] = null; +} + +// @function stopPropagation(ev: DOMEvent): this +// Stop the given event from propagation to parent elements. Used inside the listener functions: +// ```js +// L.DomEvent.on(div, 'click', function (ev) { +// L.DomEvent.stopPropagation(ev); +// }); +// ``` +function stopPropagation(e) { + + if (e.stopPropagation) { + e.stopPropagation(); + } else if (e.originalEvent) { // In case of Leaflet event. + e.originalEvent._stopped = true; + } else { + e.cancelBubble = true; + } + + return this; +} + +// @function disableScrollPropagation(el: HTMLElement): this +// Adds `stopPropagation` to the element's `'wheel'` events (plus browser variants). +function disableScrollPropagation(el) { + addOne(el, 'wheel', stopPropagation); + return this; +} + +// @function disableClickPropagation(el: HTMLElement): this +// Adds `stopPropagation` to the element's `'click'`, `'dblclick'`, `'contextmenu'`, +// `'mousedown'` and `'touchstart'` events (plus browser variants). +function disableClickPropagation(el) { + on(el, 'mousedown touchstart dblclick contextmenu', stopPropagation); + el['_leaflet_disable_click'] = true; + return this; +} + +// @function preventDefault(ev: DOMEvent): this +// Prevents the default action of the DOM Event `ev` from happening (such as +// following a link in the href of the a element, or doing a POST request +// with page reload when a `
` is submitted). +// Use it inside listener functions. +function preventDefault(e) { + if (e.preventDefault) { + e.preventDefault(); + } else { + e.returnValue = false; + } + return this; +} + +// @function stop(ev: DOMEvent): this +// Does `stopPropagation` and `preventDefault` at the same time. +function stop(e) { + preventDefault(e); + stopPropagation(e); + return this; +} + +// @function getMousePosition(ev: DOMEvent, container?: HTMLElement): Point +// Gets normalized mouse position from a DOM event relative to the +// `container` (border excluded) or to the whole page if not specified. +function getMousePosition(e, container) { + if (!container) { + return new Point(e.clientX, e.clientY); + } + + var scale = getScale(container), + offset = scale.boundingClientRect; // left and top values are in page scale (like the event clientX/Y) + + return new Point( + // offset.left/top values are in page scale (like clientX/Y), + // whereas clientLeft/Top (border width) values are the original values (before CSS scale applies). + (e.clientX - offset.left) / scale.x - container.clientLeft, + (e.clientY - offset.top) / scale.y - container.clientTop + ); +} + +// Chrome on Win scrolls double the pixels as in other platforms (see #4538), +// and Firefox scrolls device pixels, not CSS pixels +var wheelPxFactor = + (Browser.win && Browser.chrome) ? 2 * window.devicePixelRatio : + Browser.gecko ? window.devicePixelRatio : 1; + +// @function getWheelDelta(ev: DOMEvent): Number +// Gets normalized wheel delta from a wheel DOM event, in vertical +// pixels scrolled (negative if scrolling down). +// Events from pointing devices without precise scrolling are mapped to +// a best guess of 60 pixels. +function getWheelDelta(e) { + return (Browser.edge) ? e.wheelDeltaY / 2 : // Don't trust window-geometry-based delta + (e.deltaY && e.deltaMode === 0) ? -e.deltaY / wheelPxFactor : // Pixels + (e.deltaY && e.deltaMode === 1) ? -e.deltaY * 20 : // Lines + (e.deltaY && e.deltaMode === 2) ? -e.deltaY * 60 : // Pages + (e.deltaX || e.deltaZ) ? 0 : // Skip horizontal/depth wheel events + e.wheelDelta ? (e.wheelDeltaY || e.wheelDelta) / 2 : // Legacy IE pixels + (e.detail && Math.abs(e.detail) < 32765) ? -e.detail * 20 : // Legacy Moz lines + e.detail ? e.detail / -32765 * 60 : // Legacy Moz pages + 0; +} + +// check if element really left/entered the event target (for mouseenter/mouseleave) +function isExternalTarget(el, e) { + + var related = e.relatedTarget; + + if (!related) { return true; } + + try { + while (related && (related !== el)) { + related = related.parentNode; + } + } catch (err) { + return false; + } + return (related !== el); +} + +var DomEvent = { + __proto__: null, + on: on, + off: off, + stopPropagation: stopPropagation, + disableScrollPropagation: disableScrollPropagation, + disableClickPropagation: disableClickPropagation, + preventDefault: preventDefault, + stop: stop, + getMousePosition: getMousePosition, + getWheelDelta: getWheelDelta, + isExternalTarget: isExternalTarget, + addListener: on, + removeListener: off +}; + +/* + * @class PosAnimation + * @aka L.PosAnimation + * @inherits Evented + * Used internally for panning animations, utilizing CSS3 Transitions for modern browsers and a timer fallback for IE6-9. + * + * @example + * ```js + * var fx = new L.PosAnimation(); + * fx.run(el, [300, 500], 0.5); + * ``` + * + * @constructor L.PosAnimation() + * Creates a `PosAnimation` object. + * + */ + +var PosAnimation = Evented.extend({ + + // @method run(el: HTMLElement, newPos: Point, duration?: Number, easeLinearity?: Number) + // Run an animation of a given element to a new position, optionally setting + // duration in seconds (`0.25` by default) and easing linearity factor (3rd + // argument of the [cubic bezier curve](https://cubic-bezier.com/#0,0,.5,1), + // `0.5` by default). + run: function (el, newPos, duration, easeLinearity) { + this.stop(); + + this._el = el; + this._inProgress = true; + this._duration = duration || 0.25; + this._easeOutPower = 1 / Math.max(easeLinearity || 0.5, 0.2); + + this._startPos = getPosition(el); + this._offset = newPos.subtract(this._startPos); + this._startTime = +new Date(); + + // @event start: Event + // Fired when the animation starts + this.fire('start'); + + this._animate(); + }, + + // @method stop() + // Stops the animation (if currently running). + stop: function () { + if (!this._inProgress) { return; } + + this._step(true); + this._complete(); + }, + + _animate: function () { + // animation loop + this._animId = requestAnimFrame(this._animate, this); + this._step(); + }, + + _step: function (round) { + var elapsed = (+new Date()) - this._startTime, + duration = this._duration * 1000; + + if (elapsed < duration) { + this._runFrame(this._easeOut(elapsed / duration), round); + } else { + this._runFrame(1); + this._complete(); + } + }, + + _runFrame: function (progress, round) { + var pos = this._startPos.add(this._offset.multiplyBy(progress)); + if (round) { + pos._round(); + } + setPosition(this._el, pos); + + // @event step: Event + // Fired continuously during the animation. + this.fire('step'); + }, + + _complete: function () { + cancelAnimFrame(this._animId); + + this._inProgress = false; + // @event end: Event + // Fired when the animation ends. + this.fire('end'); + }, + + _easeOut: function (t) { + return 1 - Math.pow(1 - t, this._easeOutPower); + } +}); + +/* + * @class Map + * @aka L.Map + * @inherits Evented + * + * The central class of the API — it is used to create a map on a page and manipulate it. + * + * @example + * + * ```js + * // initialize the map on the "map" div with a given center and zoom + * var map = L.map('map', { + * center: [51.505, -0.09], + * zoom: 13 + * }); + * ``` + * + */ + +var Map = Evented.extend({ + + options: { + // @section Map State Options + // @option crs: CRS = L.CRS.EPSG3857 + // The [Coordinate Reference System](#crs) to use. Don't change this if you're not + // sure what it means. + crs: EPSG3857, + + // @option center: LatLng = undefined + // Initial geographic center of the map + center: undefined, + + // @option zoom: Number = undefined + // Initial map zoom level + zoom: undefined, + + // @option minZoom: Number = * + // Minimum zoom level of the map. + // If not specified and at least one `GridLayer` or `TileLayer` is in the map, + // the lowest of their `minZoom` options will be used instead. + minZoom: undefined, + + // @option maxZoom: Number = * + // Maximum zoom level of the map. + // If not specified and at least one `GridLayer` or `TileLayer` is in the map, + // the highest of their `maxZoom` options will be used instead. + maxZoom: undefined, + + // @option layers: Layer[] = [] + // Array of layers that will be added to the map initially + layers: [], + + // @option maxBounds: LatLngBounds = null + // When this option is set, the map restricts the view to the given + // geographical bounds, bouncing the user back if the user tries to pan + // outside the view. To set the restriction dynamically, use + // [`setMaxBounds`](#map-setmaxbounds) method. + maxBounds: undefined, + + // @option renderer: Renderer = * + // The default method for drawing vector layers on the map. `L.SVG` + // or `L.Canvas` by default depending on browser support. + renderer: undefined, + + + // @section Animation Options + // @option zoomAnimation: Boolean = true + // Whether the map zoom animation is enabled. By default it's enabled + // in all browsers that support CSS3 Transitions except Android. + zoomAnimation: true, + + // @option zoomAnimationThreshold: Number = 4 + // Won't animate zoom if the zoom difference exceeds this value. + zoomAnimationThreshold: 4, + + // @option fadeAnimation: Boolean = true + // Whether the tile fade animation is enabled. By default it's enabled + // in all browsers that support CSS3 Transitions except Android. + fadeAnimation: true, + + // @option markerZoomAnimation: Boolean = true + // Whether markers animate their zoom with the zoom animation, if disabled + // they will disappear for the length of the animation. By default it's + // enabled in all browsers that support CSS3 Transitions except Android. + markerZoomAnimation: true, + + // @option transform3DLimit: Number = 2^23 + // Defines the maximum size of a CSS translation transform. The default + // value should not be changed unless a web browser positions layers in + // the wrong place after doing a large `panBy`. + transform3DLimit: 8388608, // Precision limit of a 32-bit float + + // @section Interaction Options + // @option zoomSnap: Number = 1 + // Forces the map's zoom level to always be a multiple of this, particularly + // right after a [`fitBounds()`](#map-fitbounds) or a pinch-zoom. + // By default, the zoom level snaps to the nearest integer; lower values + // (e.g. `0.5` or `0.1`) allow for greater granularity. A value of `0` + // means the zoom level will not be snapped after `fitBounds` or a pinch-zoom. + zoomSnap: 1, + + // @option zoomDelta: Number = 1 + // Controls how much the map's zoom level will change after a + // [`zoomIn()`](#map-zoomin), [`zoomOut()`](#map-zoomout), pressing `+` + // or `-` on the keyboard, or using the [zoom controls](#control-zoom). + // Values smaller than `1` (e.g. `0.5`) allow for greater granularity. + zoomDelta: 1, + + // @option trackResize: Boolean = true + // Whether the map automatically handles browser window resize to update itself. + trackResize: true + }, + + initialize: function (id, options) { // (HTMLElement or String, Object) + options = setOptions(this, options); + + // Make sure to assign internal flags at the beginning, + // to avoid inconsistent state in some edge cases. + this._handlers = []; + this._layers = {}; + this._zoomBoundLayers = {}; + this._sizeChanged = true; + + this._initContainer(id); + this._initLayout(); + + // hack for https://github.com/Leaflet/Leaflet/issues/1980 + this._onResize = bind(this._onResize, this); + + this._initEvents(); + + if (options.maxBounds) { + this.setMaxBounds(options.maxBounds); + } + + if (options.zoom !== undefined) { + this._zoom = this._limitZoom(options.zoom); + } + + if (options.center && options.zoom !== undefined) { + this.setView(toLatLng(options.center), options.zoom, {reset: true}); + } + + this.callInitHooks(); + + // don't animate on browsers without hardware-accelerated transitions or old Android/Opera + this._zoomAnimated = TRANSITION && Browser.any3d && !Browser.mobileOpera && + this.options.zoomAnimation; + + // zoom transitions run with the same duration for all layers, so if one of transitionend events + // happens after starting zoom animation (propagating to the map pane), we know that it ended globally + if (this._zoomAnimated) { + this._createAnimProxy(); + on(this._proxy, TRANSITION_END, this._catchTransitionEnd, this); + } + + this._addLayers(this.options.layers); + }, + + + // @section Methods for modifying map state + + // @method setView(center: LatLng, zoom: Number, options?: Zoom/pan options): this + // Sets the view of the map (geographical center and zoom) with the given + // animation options. + setView: function (center, zoom, options) { + + zoom = zoom === undefined ? this._zoom : this._limitZoom(zoom); + center = this._limitCenter(toLatLng(center), zoom, this.options.maxBounds); + options = options || {}; + + this._stop(); + + if (this._loaded && !options.reset && options !== true) { + + if (options.animate !== undefined) { + options.zoom = extend({animate: options.animate}, options.zoom); + options.pan = extend({animate: options.animate, duration: options.duration}, options.pan); + } + + // try animating pan or zoom + var moved = (this._zoom !== zoom) ? + this._tryAnimatedZoom && this._tryAnimatedZoom(center, zoom, options.zoom) : + this._tryAnimatedPan(center, options.pan); + + if (moved) { + // prevent resize handler call, the view will refresh after animation anyway + clearTimeout(this._sizeTimer); + return this; + } + } + + // animation didn't start, just reset the map view + this._resetView(center, zoom); + + return this; + }, + + // @method setZoom(zoom: Number, options?: Zoom/pan options): this + // Sets the zoom of the map. + setZoom: function (zoom, options) { + if (!this._loaded) { + this._zoom = zoom; + return this; + } + return this.setView(this.getCenter(), zoom, {zoom: options}); + }, + + // @method zoomIn(delta?: Number, options?: Zoom options): this + // Increases the zoom of the map by `delta` ([`zoomDelta`](#map-zoomdelta) by default). + zoomIn: function (delta, options) { + delta = delta || (Browser.any3d ? this.options.zoomDelta : 1); + return this.setZoom(this._zoom + delta, options); + }, + + // @method zoomOut(delta?: Number, options?: Zoom options): this + // Decreases the zoom of the map by `delta` ([`zoomDelta`](#map-zoomdelta) by default). + zoomOut: function (delta, options) { + delta = delta || (Browser.any3d ? this.options.zoomDelta : 1); + return this.setZoom(this._zoom - delta, options); + }, + + // @method setZoomAround(latlng: LatLng, zoom: Number, options: Zoom options): this + // Zooms the map while keeping a specified geographical point on the map + // stationary (e.g. used internally for scroll zoom and double-click zoom). + // @alternative + // @method setZoomAround(offset: Point, zoom: Number, options: Zoom options): this + // Zooms the map while keeping a specified pixel on the map (relative to the top-left corner) stationary. + setZoomAround: function (latlng, zoom, options) { + var scale = this.getZoomScale(zoom), + viewHalf = this.getSize().divideBy(2), + containerPoint = latlng instanceof Point ? latlng : this.latLngToContainerPoint(latlng), + + centerOffset = containerPoint.subtract(viewHalf).multiplyBy(1 - 1 / scale), + newCenter = this.containerPointToLatLng(viewHalf.add(centerOffset)); + + return this.setView(newCenter, zoom, {zoom: options}); + }, + + _getBoundsCenterZoom: function (bounds, options) { + + options = options || {}; + bounds = bounds.getBounds ? bounds.getBounds() : toLatLngBounds(bounds); + + var paddingTL = toPoint(options.paddingTopLeft || options.padding || [0, 0]), + paddingBR = toPoint(options.paddingBottomRight || options.padding || [0, 0]), + + zoom = this.getBoundsZoom(bounds, false, paddingTL.add(paddingBR)); + + zoom = (typeof options.maxZoom === 'number') ? Math.min(options.maxZoom, zoom) : zoom; + + if (zoom === Infinity) { + return { + center: bounds.getCenter(), + zoom: zoom + }; + } + + var paddingOffset = paddingBR.subtract(paddingTL).divideBy(2), + + swPoint = this.project(bounds.getSouthWest(), zoom), + nePoint = this.project(bounds.getNorthEast(), zoom), + center = this.unproject(swPoint.add(nePoint).divideBy(2).add(paddingOffset), zoom); + + return { + center: center, + zoom: zoom + }; + }, + + // @method fitBounds(bounds: LatLngBounds, options?: fitBounds options): this + // Sets a map view that contains the given geographical bounds with the + // maximum zoom level possible. + fitBounds: function (bounds, options) { + + bounds = toLatLngBounds(bounds); + + if (!bounds.isValid()) { + throw new Error('Bounds are not valid.'); + } + + var target = this._getBoundsCenterZoom(bounds, options); + return this.setView(target.center, target.zoom, options); + }, + + // @method fitWorld(options?: fitBounds options): this + // Sets a map view that mostly contains the whole world with the maximum + // zoom level possible. + fitWorld: function (options) { + return this.fitBounds([[-90, -180], [90, 180]], options); + }, + + // @method panTo(latlng: LatLng, options?: Pan options): this + // Pans the map to a given center. + panTo: function (center, options) { // (LatLng) + return this.setView(center, this._zoom, {pan: options}); + }, + + // @method panBy(offset: Point, options?: Pan options): this + // Pans the map by a given number of pixels (animated). + panBy: function (offset, options) { + offset = toPoint(offset).round(); + options = options || {}; + + if (!offset.x && !offset.y) { + return this.fire('moveend'); + } + // If we pan too far, Chrome gets issues with tiles + // and makes them disappear or appear in the wrong place (slightly offset) #2602 + if (options.animate !== true && !this.getSize().contains(offset)) { + this._resetView(this.unproject(this.project(this.getCenter()).add(offset)), this.getZoom()); + return this; + } + + if (!this._panAnim) { + this._panAnim = new PosAnimation(); + + this._panAnim.on({ + 'step': this._onPanTransitionStep, + 'end': this._onPanTransitionEnd + }, this); + } + + // don't fire movestart if animating inertia + if (!options.noMoveStart) { + this.fire('movestart'); + } + + // animate pan unless animate: false specified + if (options.animate !== false) { + addClass(this._mapPane, 'leaflet-pan-anim'); + + var newPos = this._getMapPanePos().subtract(offset).round(); + this._panAnim.run(this._mapPane, newPos, options.duration || 0.25, options.easeLinearity); + } else { + this._rawPanBy(offset); + this.fire('move').fire('moveend'); + } + + return this; + }, + + // @method flyTo(latlng: LatLng, zoom?: Number, options?: Zoom/pan options): this + // Sets the view of the map (geographical center and zoom) performing a smooth + // pan-zoom animation. + flyTo: function (targetCenter, targetZoom, options) { + + options = options || {}; + if (options.animate === false || !Browser.any3d) { + return this.setView(targetCenter, targetZoom, options); + } + + this._stop(); + + var from = this.project(this.getCenter()), + to = this.project(targetCenter), + size = this.getSize(), + startZoom = this._zoom; + + targetCenter = toLatLng(targetCenter); + targetZoom = targetZoom === undefined ? startZoom : targetZoom; + + var w0 = Math.max(size.x, size.y), + w1 = w0 * this.getZoomScale(startZoom, targetZoom), + u1 = (to.distanceTo(from)) || 1, + rho = 1.42, + rho2 = rho * rho; + + function r(i) { + var s1 = i ? -1 : 1, + s2 = i ? w1 : w0, + t1 = w1 * w1 - w0 * w0 + s1 * rho2 * rho2 * u1 * u1, + b1 = 2 * s2 * rho2 * u1, + b = t1 / b1, + sq = Math.sqrt(b * b + 1) - b; + + // workaround for floating point precision bug when sq = 0, log = -Infinite, + // thus triggering an infinite loop in flyTo + var log = sq < 0.000000001 ? -18 : Math.log(sq); + + return log; + } + + function sinh(n) { return (Math.exp(n) - Math.exp(-n)) / 2; } + function cosh(n) { return (Math.exp(n) + Math.exp(-n)) / 2; } + function tanh(n) { return sinh(n) / cosh(n); } + + var r0 = r(0); + + function w(s) { return w0 * (cosh(r0) / cosh(r0 + rho * s)); } + function u(s) { return w0 * (cosh(r0) * tanh(r0 + rho * s) - sinh(r0)) / rho2; } + + function easeOut(t) { return 1 - Math.pow(1 - t, 1.5); } + + var start = Date.now(), + S = (r(1) - r0) / rho, + duration = options.duration ? 1000 * options.duration : 1000 * S * 0.8; + + function frame() { + var t = (Date.now() - start) / duration, + s = easeOut(t) * S; + + if (t <= 1) { + this._flyToFrame = requestAnimFrame(frame, this); + + this._move( + this.unproject(from.add(to.subtract(from).multiplyBy(u(s) / u1)), startZoom), + this.getScaleZoom(w0 / w(s), startZoom), + {flyTo: true}); + + } else { + this + ._move(targetCenter, targetZoom) + ._moveEnd(true); + } + } + + this._moveStart(true, options.noMoveStart); + + frame.call(this); + return this; + }, + + // @method flyToBounds(bounds: LatLngBounds, options?: fitBounds options): this + // Sets the view of the map with a smooth animation like [`flyTo`](#map-flyto), + // but takes a bounds parameter like [`fitBounds`](#map-fitbounds). + flyToBounds: function (bounds, options) { + var target = this._getBoundsCenterZoom(bounds, options); + return this.flyTo(target.center, target.zoom, options); + }, + + // @method setMaxBounds(bounds: LatLngBounds): this + // Restricts the map view to the given bounds (see the [maxBounds](#map-maxbounds) option). + setMaxBounds: function (bounds) { + bounds = toLatLngBounds(bounds); + + if (!bounds.isValid()) { + this.options.maxBounds = null; + return this.off('moveend', this._panInsideMaxBounds); + } else if (this.options.maxBounds) { + this.off('moveend', this._panInsideMaxBounds); + } + + this.options.maxBounds = bounds; + + if (this._loaded) { + this._panInsideMaxBounds(); + } + + return this.on('moveend', this._panInsideMaxBounds); + }, + + // @method setMinZoom(zoom: Number): this + // Sets the lower limit for the available zoom levels (see the [minZoom](#map-minzoom) option). + setMinZoom: function (zoom) { + var oldZoom = this.options.minZoom; + this.options.minZoom = zoom; + + if (this._loaded && oldZoom !== zoom) { + this.fire('zoomlevelschange'); + + if (this.getZoom() < this.options.minZoom) { + return this.setZoom(zoom); + } + } + + return this; + }, + + // @method setMaxZoom(zoom: Number): this + // Sets the upper limit for the available zoom levels (see the [maxZoom](#map-maxzoom) option). + setMaxZoom: function (zoom) { + var oldZoom = this.options.maxZoom; + this.options.maxZoom = zoom; + + if (this._loaded && oldZoom !== zoom) { + this.fire('zoomlevelschange'); + + if (this.getZoom() > this.options.maxZoom) { + return this.setZoom(zoom); + } + } + + return this; + }, + + // @method panInsideBounds(bounds: LatLngBounds, options?: Pan options): this + // Pans the map to the closest view that would lie inside the given bounds (if it's not already), controlling the animation using the options specific, if any. + panInsideBounds: function (bounds, options) { + this._enforcingBounds = true; + var center = this.getCenter(), + newCenter = this._limitCenter(center, this._zoom, toLatLngBounds(bounds)); + + if (!center.equals(newCenter)) { + this.panTo(newCenter, options); + } + + this._enforcingBounds = false; + return this; + }, + + // @method panInside(latlng: LatLng, options?: padding options): this + // Pans the map the minimum amount to make the `latlng` visible. Use + // padding options to fit the display to more restricted bounds. + // If `latlng` is already within the (optionally padded) display bounds, + // the map will not be panned. + panInside: function (latlng, options) { + options = options || {}; + + var paddingTL = toPoint(options.paddingTopLeft || options.padding || [0, 0]), + paddingBR = toPoint(options.paddingBottomRight || options.padding || [0, 0]), + pixelCenter = this.project(this.getCenter()), + pixelPoint = this.project(latlng), + pixelBounds = this.getPixelBounds(), + paddedBounds = toBounds([pixelBounds.min.add(paddingTL), pixelBounds.max.subtract(paddingBR)]), + paddedSize = paddedBounds.getSize(); + + if (!paddedBounds.contains(pixelPoint)) { + this._enforcingBounds = true; + var centerOffset = pixelPoint.subtract(paddedBounds.getCenter()); + var offset = paddedBounds.extend(pixelPoint).getSize().subtract(paddedSize); + pixelCenter.x += centerOffset.x < 0 ? -offset.x : offset.x; + pixelCenter.y += centerOffset.y < 0 ? -offset.y : offset.y; + this.panTo(this.unproject(pixelCenter), options); + this._enforcingBounds = false; + } + return this; + }, + + // @method invalidateSize(options: Zoom/pan options): this + // Checks if the map container size changed and updates the map if so — + // call it after you've changed the map size dynamically, also animating + // pan by default. If `options.pan` is `false`, panning will not occur. + // If `options.debounceMoveend` is `true`, it will delay `moveend` event so + // that it doesn't happen often even if the method is called many + // times in a row. + + // @alternative + // @method invalidateSize(animate: Boolean): this + // Checks if the map container size changed and updates the map if so — + // call it after you've changed the map size dynamically, also animating + // pan by default. + invalidateSize: function (options) { + if (!this._loaded) { return this; } + + options = extend({ + animate: false, + pan: true + }, options === true ? {animate: true} : options); + + var oldSize = this.getSize(); + this._sizeChanged = true; + this._lastCenter = null; + + var newSize = this.getSize(), + oldCenter = oldSize.divideBy(2).round(), + newCenter = newSize.divideBy(2).round(), + offset = oldCenter.subtract(newCenter); + + if (!offset.x && !offset.y) { return this; } + + if (options.animate && options.pan) { + this.panBy(offset); + + } else { + if (options.pan) { + this._rawPanBy(offset); + } + + this.fire('move'); + + if (options.debounceMoveend) { + clearTimeout(this._sizeTimer); + this._sizeTimer = setTimeout(bind(this.fire, this, 'moveend'), 200); + } else { + this.fire('moveend'); + } + } + + // @section Map state change events + // @event resize: ResizeEvent + // Fired when the map is resized. + return this.fire('resize', { + oldSize: oldSize, + newSize: newSize + }); + }, + + // @section Methods for modifying map state + // @method stop(): this + // Stops the currently running `panTo` or `flyTo` animation, if any. + stop: function () { + this.setZoom(this._limitZoom(this._zoom)); + if (!this.options.zoomSnap) { + this.fire('viewreset'); + } + return this._stop(); + }, + + // @section Geolocation methods + // @method locate(options?: Locate options): this + // Tries to locate the user using the Geolocation API, firing a [`locationfound`](#map-locationfound) + // event with location data on success or a [`locationerror`](#map-locationerror) event on failure, + // and optionally sets the map view to the user's location with respect to + // detection accuracy (or to the world view if geolocation failed). + // Note that, if your page doesn't use HTTPS, this method will fail in + // modern browsers ([Chrome 50 and newer](https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins)) + // See `Locate options` for more details. + locate: function (options) { + + options = this._locateOptions = extend({ + timeout: 10000, + watch: false + // setView: false + // maxZoom: + // maximumAge: 0 + // enableHighAccuracy: false + }, options); + + if (!('geolocation' in navigator)) { + this._handleGeolocationError({ + code: 0, + message: 'Geolocation not supported.' + }); + return this; + } + + var onResponse = bind(this._handleGeolocationResponse, this), + onError = bind(this._handleGeolocationError, this); + + if (options.watch) { + this._locationWatchId = + navigator.geolocation.watchPosition(onResponse, onError, options); + } else { + navigator.geolocation.getCurrentPosition(onResponse, onError, options); + } + return this; + }, + + // @method stopLocate(): this + // Stops watching location previously initiated by `map.locate({watch: true})` + // and aborts resetting the map view if map.locate was called with + // `{setView: true}`. + stopLocate: function () { + if (navigator.geolocation && navigator.geolocation.clearWatch) { + navigator.geolocation.clearWatch(this._locationWatchId); + } + if (this._locateOptions) { + this._locateOptions.setView = false; + } + return this; + }, + + _handleGeolocationError: function (error) { + if (!this._container._leaflet_id) { return; } + + var c = error.code, + message = error.message || + (c === 1 ? 'permission denied' : + (c === 2 ? 'position unavailable' : 'timeout')); + + if (this._locateOptions.setView && !this._loaded) { + this.fitWorld(); + } + + // @section Location events + // @event locationerror: ErrorEvent + // Fired when geolocation (using the [`locate`](#map-locate) method) failed. + this.fire('locationerror', { + code: c, + message: 'Geolocation error: ' + message + '.' + }); + }, + + _handleGeolocationResponse: function (pos) { + if (!this._container._leaflet_id) { return; } + + var lat = pos.coords.latitude, + lng = pos.coords.longitude, + latlng = new LatLng(lat, lng), + bounds = latlng.toBounds(pos.coords.accuracy * 2), + options = this._locateOptions; + + if (options.setView) { + var zoom = this.getBoundsZoom(bounds); + this.setView(latlng, options.maxZoom ? Math.min(zoom, options.maxZoom) : zoom); + } + + var data = { + latlng: latlng, + bounds: bounds, + timestamp: pos.timestamp + }; + + for (var i in pos.coords) { + if (typeof pos.coords[i] === 'number') { + data[i] = pos.coords[i]; + } + } + + // @event locationfound: LocationEvent + // Fired when geolocation (using the [`locate`](#map-locate) method) + // went successfully. + this.fire('locationfound', data); + }, + + // TODO Appropriate docs section? + // @section Other Methods + // @method addHandler(name: String, HandlerClass: Function): this + // Adds a new `Handler` to the map, given its name and constructor function. + addHandler: function (name, HandlerClass) { + if (!HandlerClass) { return this; } + + var handler = this[name] = new HandlerClass(this); + + this._handlers.push(handler); + + if (this.options[name]) { + handler.enable(); + } + + return this; + }, + + // @method remove(): this + // Destroys the map and clears all related event listeners. + remove: function () { + + this._initEvents(true); + if (this.options.maxBounds) { this.off('moveend', this._panInsideMaxBounds); } + + if (this._containerId !== this._container._leaflet_id) { + throw new Error('Map container is being reused by another instance'); + } + + try { + // throws error in IE6-8 + delete this._container._leaflet_id; + delete this._containerId; + } catch (e) { + /*eslint-disable */ + this._container._leaflet_id = undefined; + /* eslint-enable */ + this._containerId = undefined; + } + + if (this._locationWatchId !== undefined) { + this.stopLocate(); + } + + this._stop(); + + remove(this._mapPane); + + if (this._clearControlPos) { + this._clearControlPos(); + } + if (this._resizeRequest) { + cancelAnimFrame(this._resizeRequest); + this._resizeRequest = null; + } + + this._clearHandlers(); + + if (this._loaded) { + // @section Map state change events + // @event unload: Event + // Fired when the map is destroyed with [remove](#map-remove) method. + this.fire('unload'); + } + + var i; + for (i in this._layers) { + this._layers[i].remove(); + } + for (i in this._panes) { + remove(this._panes[i]); + } + + this._layers = []; + this._panes = []; + delete this._mapPane; + delete this._renderer; + + return this; + }, + + // @section Other Methods + // @method createPane(name: String, container?: HTMLElement): HTMLElement + // Creates a new [map pane](#map-pane) with the given name if it doesn't exist already, + // then returns it. The pane is created as a child of `container`, or + // as a child of the main map pane if not set. + createPane: function (name, container) { + var className = 'leaflet-pane' + (name ? ' leaflet-' + name.replace('Pane', '') + '-pane' : ''), + pane = create$1('div', className, container || this._mapPane); + + if (name) { + this._panes[name] = pane; + } + return pane; + }, + + // @section Methods for Getting Map State + + // @method getCenter(): LatLng + // Returns the geographical center of the map view + getCenter: function () { + this._checkIfLoaded(); + + if (this._lastCenter && !this._moved()) { + return this._lastCenter; + } + return this.layerPointToLatLng(this._getCenterLayerPoint()); + }, + + // @method getZoom(): Number + // Returns the current zoom level of the map view + getZoom: function () { + return this._zoom; + }, + + // @method getBounds(): LatLngBounds + // Returns the geographical bounds visible in the current map view + getBounds: function () { + var bounds = this.getPixelBounds(), + sw = this.unproject(bounds.getBottomLeft()), + ne = this.unproject(bounds.getTopRight()); + + return new LatLngBounds(sw, ne); + }, + + // @method getMinZoom(): Number + // Returns the minimum zoom level of the map (if set in the `minZoom` option of the map or of any layers), or `0` by default. + getMinZoom: function () { + return this.options.minZoom === undefined ? this._layersMinZoom || 0 : this.options.minZoom; + }, + + // @method getMaxZoom(): Number + // Returns the maximum zoom level of the map (if set in the `maxZoom` option of the map or of any layers). + getMaxZoom: function () { + return this.options.maxZoom === undefined ? + (this._layersMaxZoom === undefined ? Infinity : this._layersMaxZoom) : + this.options.maxZoom; + }, + + // @method getBoundsZoom(bounds: LatLngBounds, inside?: Boolean, padding?: Point): Number + // Returns the maximum zoom level on which the given bounds fit to the map + // view in its entirety. If `inside` (optional) is set to `true`, the method + // instead returns the minimum zoom level on which the map view fits into + // the given bounds in its entirety. + getBoundsZoom: function (bounds, inside, padding) { // (LatLngBounds[, Boolean, Point]) -> Number + bounds = toLatLngBounds(bounds); + padding = toPoint(padding || [0, 0]); + + var zoom = this.getZoom() || 0, + min = this.getMinZoom(), + max = this.getMaxZoom(), + nw = bounds.getNorthWest(), + se = bounds.getSouthEast(), + size = this.getSize().subtract(padding), + boundsSize = toBounds(this.project(se, zoom), this.project(nw, zoom)).getSize(), + snap = Browser.any3d ? this.options.zoomSnap : 1, + scalex = size.x / boundsSize.x, + scaley = size.y / boundsSize.y, + scale = inside ? Math.max(scalex, scaley) : Math.min(scalex, scaley); + + zoom = this.getScaleZoom(scale, zoom); + + if (snap) { + zoom = Math.round(zoom / (snap / 100)) * (snap / 100); // don't jump if within 1% of a snap level + zoom = inside ? Math.ceil(zoom / snap) * snap : Math.floor(zoom / snap) * snap; + } + + return Math.max(min, Math.min(max, zoom)); + }, + + // @method getSize(): Point + // Returns the current size of the map container (in pixels). + getSize: function () { + if (!this._size || this._sizeChanged) { + this._size = new Point( + this._container.clientWidth || 0, + this._container.clientHeight || 0); + + this._sizeChanged = false; + } + return this._size.clone(); + }, + + // @method getPixelBounds(): Bounds + // Returns the bounds of the current map view in projected pixel + // coordinates (sometimes useful in layer and overlay implementations). + getPixelBounds: function (center, zoom) { + var topLeftPoint = this._getTopLeftPoint(center, zoom); + return new Bounds(topLeftPoint, topLeftPoint.add(this.getSize())); + }, + + // TODO: Check semantics - isn't the pixel origin the 0,0 coord relative to + // the map pane? "left point of the map layer" can be confusing, specially + // since there can be negative offsets. + // @method getPixelOrigin(): Point + // Returns the projected pixel coordinates of the top left point of + // the map layer (useful in custom layer and overlay implementations). + getPixelOrigin: function () { + this._checkIfLoaded(); + return this._pixelOrigin; + }, + + // @method getPixelWorldBounds(zoom?: Number): Bounds + // Returns the world's bounds in pixel coordinates for zoom level `zoom`. + // If `zoom` is omitted, the map's current zoom level is used. + getPixelWorldBounds: function (zoom) { + return this.options.crs.getProjectedBounds(zoom === undefined ? this.getZoom() : zoom); + }, + + // @section Other Methods + + // @method getPane(pane: String|HTMLElement): HTMLElement + // Returns a [map pane](#map-pane), given its name or its HTML element (its identity). + getPane: function (pane) { + return typeof pane === 'string' ? this._panes[pane] : pane; + }, + + // @method getPanes(): Object + // Returns a plain object containing the names of all [panes](#map-pane) as keys and + // the panes as values. + getPanes: function () { + return this._panes; + }, + + // @method getContainer: HTMLElement + // Returns the HTML element that contains the map. + getContainer: function () { + return this._container; + }, + + + // @section Conversion Methods + + // @method getZoomScale(toZoom: Number, fromZoom: Number): Number + // Returns the scale factor to be applied to a map transition from zoom level + // `fromZoom` to `toZoom`. Used internally to help with zoom animations. + getZoomScale: function (toZoom, fromZoom) { + // TODO replace with universal implementation after refactoring projections + var crs = this.options.crs; + fromZoom = fromZoom === undefined ? this._zoom : fromZoom; + return crs.scale(toZoom) / crs.scale(fromZoom); + }, + + // @method getScaleZoom(scale: Number, fromZoom: Number): Number + // Returns the zoom level that the map would end up at, if it is at `fromZoom` + // level and everything is scaled by a factor of `scale`. Inverse of + // [`getZoomScale`](#map-getZoomScale). + getScaleZoom: function (scale, fromZoom) { + var crs = this.options.crs; + fromZoom = fromZoom === undefined ? this._zoom : fromZoom; + var zoom = crs.zoom(scale * crs.scale(fromZoom)); + return isNaN(zoom) ? Infinity : zoom; + }, + + // @method project(latlng: LatLng, zoom: Number): Point + // Projects a geographical coordinate `LatLng` according to the projection + // of the map's CRS, then scales it according to `zoom` and the CRS's + // `Transformation`. The result is pixel coordinate relative to + // the CRS origin. + project: function (latlng, zoom) { + zoom = zoom === undefined ? this._zoom : zoom; + return this.options.crs.latLngToPoint(toLatLng(latlng), zoom); + }, + + // @method unproject(point: Point, zoom: Number): LatLng + // Inverse of [`project`](#map-project). + unproject: function (point, zoom) { + zoom = zoom === undefined ? this._zoom : zoom; + return this.options.crs.pointToLatLng(toPoint(point), zoom); + }, + + // @method layerPointToLatLng(point: Point): LatLng + // Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin), + // returns the corresponding geographical coordinate (for the current zoom level). + layerPointToLatLng: function (point) { + var projectedPoint = toPoint(point).add(this.getPixelOrigin()); + return this.unproject(projectedPoint); + }, + + // @method latLngToLayerPoint(latlng: LatLng): Point + // Given a geographical coordinate, returns the corresponding pixel coordinate + // relative to the [origin pixel](#map-getpixelorigin). + latLngToLayerPoint: function (latlng) { + var projectedPoint = this.project(toLatLng(latlng))._round(); + return projectedPoint._subtract(this.getPixelOrigin()); + }, + + // @method wrapLatLng(latlng: LatLng): LatLng + // Returns a `LatLng` where `lat` and `lng` has been wrapped according to the + // map's CRS's `wrapLat` and `wrapLng` properties, if they are outside the + // CRS's bounds. + // By default this means longitude is wrapped around the dateline so its + // value is between -180 and +180 degrees. + wrapLatLng: function (latlng) { + return this.options.crs.wrapLatLng(toLatLng(latlng)); + }, + + // @method wrapLatLngBounds(bounds: LatLngBounds): LatLngBounds + // Returns a `LatLngBounds` with the same size as the given one, ensuring that + // its center is within the CRS's bounds. + // By default this means the center longitude is wrapped around the dateline so its + // value is between -180 and +180 degrees, and the majority of the bounds + // overlaps the CRS's bounds. + wrapLatLngBounds: function (latlng) { + return this.options.crs.wrapLatLngBounds(toLatLngBounds(latlng)); + }, + + // @method distance(latlng1: LatLng, latlng2: LatLng): Number + // Returns the distance between two geographical coordinates according to + // the map's CRS. By default this measures distance in meters. + distance: function (latlng1, latlng2) { + return this.options.crs.distance(toLatLng(latlng1), toLatLng(latlng2)); + }, + + // @method containerPointToLayerPoint(point: Point): Point + // Given a pixel coordinate relative to the map container, returns the corresponding + // pixel coordinate relative to the [origin pixel](#map-getpixelorigin). + containerPointToLayerPoint: function (point) { // (Point) + return toPoint(point).subtract(this._getMapPanePos()); + }, + + // @method layerPointToContainerPoint(point: Point): Point + // Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin), + // returns the corresponding pixel coordinate relative to the map container. + layerPointToContainerPoint: function (point) { // (Point) + return toPoint(point).add(this._getMapPanePos()); + }, + + // @method containerPointToLatLng(point: Point): LatLng + // Given a pixel coordinate relative to the map container, returns + // the corresponding geographical coordinate (for the current zoom level). + containerPointToLatLng: function (point) { + var layerPoint = this.containerPointToLayerPoint(toPoint(point)); + return this.layerPointToLatLng(layerPoint); + }, + + // @method latLngToContainerPoint(latlng: LatLng): Point + // Given a geographical coordinate, returns the corresponding pixel coordinate + // relative to the map container. + latLngToContainerPoint: function (latlng) { + return this.layerPointToContainerPoint(this.latLngToLayerPoint(toLatLng(latlng))); + }, + + // @method mouseEventToContainerPoint(ev: MouseEvent): Point + // Given a MouseEvent object, returns the pixel coordinate relative to the + // map container where the event took place. + mouseEventToContainerPoint: function (e) { + return getMousePosition(e, this._container); + }, + + // @method mouseEventToLayerPoint(ev: MouseEvent): Point + // Given a MouseEvent object, returns the pixel coordinate relative to + // the [origin pixel](#map-getpixelorigin) where the event took place. + mouseEventToLayerPoint: function (e) { + return this.containerPointToLayerPoint(this.mouseEventToContainerPoint(e)); + }, + + // @method mouseEventToLatLng(ev: MouseEvent): LatLng + // Given a MouseEvent object, returns geographical coordinate where the + // event took place. + mouseEventToLatLng: function (e) { // (MouseEvent) + return this.layerPointToLatLng(this.mouseEventToLayerPoint(e)); + }, + + + // map initialization methods + + _initContainer: function (id) { + var container = this._container = get(id); + + if (!container) { + throw new Error('Map container not found.'); + } else if (container._leaflet_id) { + throw new Error('Map container is already initialized.'); + } + + on(container, 'scroll', this._onScroll, this); + this._containerId = stamp(container); + }, + + _initLayout: function () { + var container = this._container; + + this._fadeAnimated = this.options.fadeAnimation && Browser.any3d; + + addClass(container, 'leaflet-container' + + (Browser.touch ? ' leaflet-touch' : '') + + (Browser.retina ? ' leaflet-retina' : '') + + (Browser.ielt9 ? ' leaflet-oldie' : '') + + (Browser.safari ? ' leaflet-safari' : '') + + (this._fadeAnimated ? ' leaflet-fade-anim' : '')); + + var position = getStyle(container, 'position'); + + if (position !== 'absolute' && position !== 'relative' && position !== 'fixed') { + container.style.position = 'relative'; + } + + this._initPanes(); + + if (this._initControlPos) { + this._initControlPos(); + } + }, + + _initPanes: function () { + var panes = this._panes = {}; + this._paneRenderers = {}; + + // @section + // + // Panes are DOM elements used to control the ordering of layers on the map. You + // can access panes with [`map.getPane`](#map-getpane) or + // [`map.getPanes`](#map-getpanes) methods. New panes can be created with the + // [`map.createPane`](#map-createpane) method. + // + // Every map has the following default panes that differ only in zIndex. + // + // @pane mapPane: HTMLElement = 'auto' + // Pane that contains all other map panes + + this._mapPane = this.createPane('mapPane', this._container); + setPosition(this._mapPane, new Point(0, 0)); + + // @pane tilePane: HTMLElement = 200 + // Pane for `GridLayer`s and `TileLayer`s + this.createPane('tilePane'); + // @pane overlayPane: HTMLElement = 400 + // Pane for vectors (`Path`s, like `Polyline`s and `Polygon`s), `ImageOverlay`s and `VideoOverlay`s + this.createPane('overlayPane'); + // @pane shadowPane: HTMLElement = 500 + // Pane for overlay shadows (e.g. `Marker` shadows) + this.createPane('shadowPane'); + // @pane markerPane: HTMLElement = 600 + // Pane for `Icon`s of `Marker`s + this.createPane('markerPane'); + // @pane tooltipPane: HTMLElement = 650 + // Pane for `Tooltip`s. + this.createPane('tooltipPane'); + // @pane popupPane: HTMLElement = 700 + // Pane for `Popup`s. + this.createPane('popupPane'); + + if (!this.options.markerZoomAnimation) { + addClass(panes.markerPane, 'leaflet-zoom-hide'); + addClass(panes.shadowPane, 'leaflet-zoom-hide'); + } + }, + + + // private methods that modify map state + + // @section Map state change events + _resetView: function (center, zoom) { + setPosition(this._mapPane, new Point(0, 0)); + + var loading = !this._loaded; + this._loaded = true; + zoom = this._limitZoom(zoom); + + this.fire('viewprereset'); + + var zoomChanged = this._zoom !== zoom; + this + ._moveStart(zoomChanged, false) + ._move(center, zoom) + ._moveEnd(zoomChanged); + + // @event viewreset: Event + // Fired when the map needs to redraw its content (this usually happens + // on map zoom or load). Very useful for creating custom overlays. + this.fire('viewreset'); + + // @event load: Event + // Fired when the map is initialized (when its center and zoom are set + // for the first time). + if (loading) { + this.fire('load'); + } + }, + + _moveStart: function (zoomChanged, noMoveStart) { + // @event zoomstart: Event + // Fired when the map zoom is about to change (e.g. before zoom animation). + // @event movestart: Event + // Fired when the view of the map starts changing (e.g. user starts dragging the map). + if (zoomChanged) { + this.fire('zoomstart'); + } + if (!noMoveStart) { + this.fire('movestart'); + } + return this; + }, + + _move: function (center, zoom, data, supressEvent) { + if (zoom === undefined) { + zoom = this._zoom; + } + var zoomChanged = this._zoom !== zoom; + + this._zoom = zoom; + this._lastCenter = center; + this._pixelOrigin = this._getNewPixelOrigin(center); + + if (!supressEvent) { + // @event zoom: Event + // Fired repeatedly during any change in zoom level, + // including zoom and fly animations. + if (zoomChanged || (data && data.pinch)) { // Always fire 'zoom' if pinching because #3530 + this.fire('zoom', data); + } + + // @event move: Event + // Fired repeatedly during any movement of the map, + // including pan and fly animations. + this.fire('move', data); + } else if (data && data.pinch) { // Always fire 'zoom' if pinching because #3530 + this.fire('zoom', data); + } + return this; + }, + + _moveEnd: function (zoomChanged) { + // @event zoomend: Event + // Fired when the map zoom changed, after any animations. + if (zoomChanged) { + this.fire('zoomend'); + } + + // @event moveend: Event + // Fired when the center of the map stops changing + // (e.g. user stopped dragging the map or after non-centered zoom). + return this.fire('moveend'); + }, + + _stop: function () { + cancelAnimFrame(this._flyToFrame); + if (this._panAnim) { + this._panAnim.stop(); + } + return this; + }, + + _rawPanBy: function (offset) { + setPosition(this._mapPane, this._getMapPanePos().subtract(offset)); + }, + + _getZoomSpan: function () { + return this.getMaxZoom() - this.getMinZoom(); + }, + + _panInsideMaxBounds: function () { + if (!this._enforcingBounds) { + this.panInsideBounds(this.options.maxBounds); + } + }, + + _checkIfLoaded: function () { + if (!this._loaded) { + throw new Error('Set map center and zoom first.'); + } + }, + + // DOM event handling + + // @section Interaction events + _initEvents: function (remove) { + this._targets = {}; + this._targets[stamp(this._container)] = this; + + var onOff = remove ? off : on; + + // @event click: MouseEvent + // Fired when the user clicks (or taps) the map. + // @event dblclick: MouseEvent + // Fired when the user double-clicks (or double-taps) the map. + // @event mousedown: MouseEvent + // Fired when the user pushes the mouse button on the map. + // @event mouseup: MouseEvent + // Fired when the user releases the mouse button on the map. + // @event mouseover: MouseEvent + // Fired when the mouse enters the map. + // @event mouseout: MouseEvent + // Fired when the mouse leaves the map. + // @event mousemove: MouseEvent + // Fired while the mouse moves over the map. + // @event contextmenu: MouseEvent + // Fired when the user pushes the right mouse button on the map, prevents + // default browser context menu from showing if there are listeners on + // this event. Also fired on mobile when the user holds a single touch + // for a second (also called long press). + // @event keypress: KeyboardEvent + // Fired when the user presses a key from the keyboard that produces a character value while the map is focused. + // @event keydown: KeyboardEvent + // Fired when the user presses a key from the keyboard while the map is focused. Unlike the `keypress` event, + // the `keydown` event is fired for keys that produce a character value and for keys + // that do not produce a character value. + // @event keyup: KeyboardEvent + // Fired when the user releases a key from the keyboard while the map is focused. + onOff(this._container, 'click dblclick mousedown mouseup ' + + 'mouseover mouseout mousemove contextmenu keypress keydown keyup', this._handleDOMEvent, this); + + if (this.options.trackResize) { + onOff(window, 'resize', this._onResize, this); + } + + if (Browser.any3d && this.options.transform3DLimit) { + (remove ? this.off : this.on).call(this, 'moveend', this._onMoveEnd); + } + }, + + _onResize: function () { + cancelAnimFrame(this._resizeRequest); + this._resizeRequest = requestAnimFrame( + function () { this.invalidateSize({debounceMoveend: true}); }, this); + }, + + _onScroll: function () { + this._container.scrollTop = 0; + this._container.scrollLeft = 0; + }, + + _onMoveEnd: function () { + var pos = this._getMapPanePos(); + if (Math.max(Math.abs(pos.x), Math.abs(pos.y)) >= this.options.transform3DLimit) { + // https://bugzilla.mozilla.org/show_bug.cgi?id=1203873 but Webkit also have + // a pixel offset on very high values, see: https://jsfiddle.net/dg6r5hhb/ + this._resetView(this.getCenter(), this.getZoom()); + } + }, + + _findEventTargets: function (e, type) { + var targets = [], + target, + isHover = type === 'mouseout' || type === 'mouseover', + src = e.target || e.srcElement, + dragging = false; + + while (src) { + target = this._targets[stamp(src)]; + if (target && (type === 'click' || type === 'preclick') && this._draggableMoved(target)) { + // Prevent firing click after you just dragged an object. + dragging = true; + break; + } + if (target && target.listens(type, true)) { + if (isHover && !isExternalTarget(src, e)) { break; } + targets.push(target); + if (isHover) { break; } + } + if (src === this._container) { break; } + src = src.parentNode; + } + if (!targets.length && !dragging && !isHover && this.listens(type, true)) { + targets = [this]; + } + return targets; + }, + + _isClickDisabled: function (el) { + while (el !== this._container) { + if (el['_leaflet_disable_click']) { return true; } + el = el.parentNode; + } + }, + + _handleDOMEvent: function (e) { + var el = (e.target || e.srcElement); + if (!this._loaded || el['_leaflet_disable_events'] || e.type === 'click' && this._isClickDisabled(el)) { + return; + } + + var type = e.type; + + if (type === 'mousedown') { + // prevents outline when clicking on keyboard-focusable element + preventOutline(el); + } + + this._fireDOMEvent(e, type); + }, + + _mouseEvents: ['click', 'dblclick', 'mouseover', 'mouseout', 'contextmenu'], + + _fireDOMEvent: function (e, type, canvasTargets) { + + if (e.type === 'click') { + // Fire a synthetic 'preclick' event which propagates up (mainly for closing popups). + // @event preclick: MouseEvent + // Fired before mouse click on the map (sometimes useful when you + // want something to happen on click before any existing click + // handlers start running). + var synth = extend({}, e); + synth.type = 'preclick'; + this._fireDOMEvent(synth, synth.type, canvasTargets); + } + + // Find the layer the event is propagating from and its parents. + var targets = this._findEventTargets(e, type); + + if (canvasTargets) { + var filtered = []; // pick only targets with listeners + for (var i = 0; i < canvasTargets.length; i++) { + if (canvasTargets[i].listens(type, true)) { + filtered.push(canvasTargets[i]); + } + } + targets = filtered.concat(targets); + } + + if (!targets.length) { return; } + + if (type === 'contextmenu') { + preventDefault(e); + } + + var target = targets[0]; + var data = { + originalEvent: e + }; + + if (e.type !== 'keypress' && e.type !== 'keydown' && e.type !== 'keyup') { + var isMarker = target.getLatLng && (!target._radius || target._radius <= 10); + data.containerPoint = isMarker ? + this.latLngToContainerPoint(target.getLatLng()) : this.mouseEventToContainerPoint(e); + data.layerPoint = this.containerPointToLayerPoint(data.containerPoint); + data.latlng = isMarker ? target.getLatLng() : this.layerPointToLatLng(data.layerPoint); + } + + for (i = 0; i < targets.length; i++) { + targets[i].fire(type, data, true); + if (data.originalEvent._stopped || + (targets[i].options.bubblingMouseEvents === false && indexOf(this._mouseEvents, type) !== -1)) { return; } + } + }, + + _draggableMoved: function (obj) { + obj = obj.dragging && obj.dragging.enabled() ? obj : this; + return (obj.dragging && obj.dragging.moved()) || (this.boxZoom && this.boxZoom.moved()); + }, + + _clearHandlers: function () { + for (var i = 0, len = this._handlers.length; i < len; i++) { + this._handlers[i].disable(); + } + }, + + // @section Other Methods + + // @method whenReady(fn: Function, context?: Object): this + // Runs the given function `fn` when the map gets initialized with + // a view (center and zoom) and at least one layer, or immediately + // if it's already initialized, optionally passing a function context. + whenReady: function (callback, context) { + if (this._loaded) { + callback.call(context || this, {target: this}); + } else { + this.on('load', callback, context); + } + return this; + }, + + + // private methods for getting map state + + _getMapPanePos: function () { + return getPosition(this._mapPane) || new Point(0, 0); + }, + + _moved: function () { + var pos = this._getMapPanePos(); + return pos && !pos.equals([0, 0]); + }, + + _getTopLeftPoint: function (center, zoom) { + var pixelOrigin = center && zoom !== undefined ? + this._getNewPixelOrigin(center, zoom) : + this.getPixelOrigin(); + return pixelOrigin.subtract(this._getMapPanePos()); + }, + + _getNewPixelOrigin: function (center, zoom) { + var viewHalf = this.getSize()._divideBy(2); + return this.project(center, zoom)._subtract(viewHalf)._add(this._getMapPanePos())._round(); + }, + + _latLngToNewLayerPoint: function (latlng, zoom, center) { + var topLeft = this._getNewPixelOrigin(center, zoom); + return this.project(latlng, zoom)._subtract(topLeft); + }, + + _latLngBoundsToNewLayerBounds: function (latLngBounds, zoom, center) { + var topLeft = this._getNewPixelOrigin(center, zoom); + return toBounds([ + this.project(latLngBounds.getSouthWest(), zoom)._subtract(topLeft), + this.project(latLngBounds.getNorthWest(), zoom)._subtract(topLeft), + this.project(latLngBounds.getSouthEast(), zoom)._subtract(topLeft), + this.project(latLngBounds.getNorthEast(), zoom)._subtract(topLeft) + ]); + }, + + // layer point of the current center + _getCenterLayerPoint: function () { + return this.containerPointToLayerPoint(this.getSize()._divideBy(2)); + }, + + // offset of the specified place to the current center in pixels + _getCenterOffset: function (latlng) { + return this.latLngToLayerPoint(latlng).subtract(this._getCenterLayerPoint()); + }, + + // adjust center for view to get inside bounds + _limitCenter: function (center, zoom, bounds) { + + if (!bounds) { return center; } + + var centerPoint = this.project(center, zoom), + viewHalf = this.getSize().divideBy(2), + viewBounds = new Bounds(centerPoint.subtract(viewHalf), centerPoint.add(viewHalf)), + offset = this._getBoundsOffset(viewBounds, bounds, zoom); + + // If offset is less than a pixel, ignore. + // This prevents unstable projections from getting into + // an infinite loop of tiny offsets. + if (offset.round().equals([0, 0])) { + return center; + } + + return this.unproject(centerPoint.add(offset), zoom); + }, + + // adjust offset for view to get inside bounds + _limitOffset: function (offset, bounds) { + if (!bounds) { return offset; } + + var viewBounds = this.getPixelBounds(), + newBounds = new Bounds(viewBounds.min.add(offset), viewBounds.max.add(offset)); + + return offset.add(this._getBoundsOffset(newBounds, bounds)); + }, + + // returns offset needed for pxBounds to get inside maxBounds at a specified zoom + _getBoundsOffset: function (pxBounds, maxBounds, zoom) { + var projectedMaxBounds = toBounds( + this.project(maxBounds.getNorthEast(), zoom), + this.project(maxBounds.getSouthWest(), zoom) + ), + minOffset = projectedMaxBounds.min.subtract(pxBounds.min), + maxOffset = projectedMaxBounds.max.subtract(pxBounds.max), + + dx = this._rebound(minOffset.x, -maxOffset.x), + dy = this._rebound(minOffset.y, -maxOffset.y); + + return new Point(dx, dy); + }, + + _rebound: function (left, right) { + return left + right > 0 ? + Math.round(left - right) / 2 : + Math.max(0, Math.ceil(left)) - Math.max(0, Math.floor(right)); + }, + + _limitZoom: function (zoom) { + var min = this.getMinZoom(), + max = this.getMaxZoom(), + snap = Browser.any3d ? this.options.zoomSnap : 1; + if (snap) { + zoom = Math.round(zoom / snap) * snap; + } + return Math.max(min, Math.min(max, zoom)); + }, + + _onPanTransitionStep: function () { + this.fire('move'); + }, + + _onPanTransitionEnd: function () { + removeClass(this._mapPane, 'leaflet-pan-anim'); + this.fire('moveend'); + }, + + _tryAnimatedPan: function (center, options) { + // difference between the new and current centers in pixels + var offset = this._getCenterOffset(center)._trunc(); + + // don't animate too far unless animate: true specified in options + if ((options && options.animate) !== true && !this.getSize().contains(offset)) { return false; } + + this.panBy(offset, options); + + return true; + }, + + _createAnimProxy: function () { + + var proxy = this._proxy = create$1('div', 'leaflet-proxy leaflet-zoom-animated'); + this._panes.mapPane.appendChild(proxy); + + this.on('zoomanim', function (e) { + var prop = TRANSFORM, + transform = this._proxy.style[prop]; + + setTransform(this._proxy, this.project(e.center, e.zoom), this.getZoomScale(e.zoom, 1)); + + // workaround for case when transform is the same and so transitionend event is not fired + if (transform === this._proxy.style[prop] && this._animatingZoom) { + this._onZoomTransitionEnd(); + } + }, this); + + this.on('load moveend', this._animMoveEnd, this); + + this._on('unload', this._destroyAnimProxy, this); + }, + + _destroyAnimProxy: function () { + remove(this._proxy); + this.off('load moveend', this._animMoveEnd, this); + delete this._proxy; + }, + + _animMoveEnd: function () { + var c = this.getCenter(), + z = this.getZoom(); + setTransform(this._proxy, this.project(c, z), this.getZoomScale(z, 1)); + }, + + _catchTransitionEnd: function (e) { + if (this._animatingZoom && e.propertyName.indexOf('transform') >= 0) { + this._onZoomTransitionEnd(); + } + }, + + _nothingToAnimate: function () { + return !this._container.getElementsByClassName('leaflet-zoom-animated').length; + }, + + _tryAnimatedZoom: function (center, zoom, options) { + + if (this._animatingZoom) { return true; } + + options = options || {}; + + // don't animate if disabled, not supported or zoom difference is too large + if (!this._zoomAnimated || options.animate === false || this._nothingToAnimate() || + Math.abs(zoom - this._zoom) > this.options.zoomAnimationThreshold) { return false; } + + // offset is the pixel coords of the zoom origin relative to the current center + var scale = this.getZoomScale(zoom), + offset = this._getCenterOffset(center)._divideBy(1 - 1 / scale); + + // don't animate if the zoom origin isn't within one screen from the current center, unless forced + if (options.animate !== true && !this.getSize().contains(offset)) { return false; } + + requestAnimFrame(function () { + this + ._moveStart(true, false) + ._animateZoom(center, zoom, true); + }, this); + + return true; + }, + + _animateZoom: function (center, zoom, startAnim, noUpdate) { + if (!this._mapPane) { return; } + + if (startAnim) { + this._animatingZoom = true; + + // remember what center/zoom to set after animation + this._animateToCenter = center; + this._animateToZoom = zoom; + + addClass(this._mapPane, 'leaflet-zoom-anim'); + } + + // @section Other Events + // @event zoomanim: ZoomAnimEvent + // Fired at least once per zoom animation. For continuous zoom, like pinch zooming, fired once per frame during zoom. + this.fire('zoomanim', { + center: center, + zoom: zoom, + noUpdate: noUpdate + }); + + if (!this._tempFireZoomEvent) { + this._tempFireZoomEvent = this._zoom !== this._animateToZoom; + } + + this._move(this._animateToCenter, this._animateToZoom, undefined, true); + + // Work around webkit not firing 'transitionend', see https://github.com/Leaflet/Leaflet/issues/3689, 2693 + setTimeout(bind(this._onZoomTransitionEnd, this), 250); + }, + + _onZoomTransitionEnd: function () { + if (!this._animatingZoom) { return; } + + if (this._mapPane) { + removeClass(this._mapPane, 'leaflet-zoom-anim'); + } + + this._animatingZoom = false; + + this._move(this._animateToCenter, this._animateToZoom, undefined, true); + + if (this._tempFireZoomEvent) { + this.fire('zoom'); + } + delete this._tempFireZoomEvent; + + this.fire('move'); + + this._moveEnd(true); + } +}); + +// @section + +// @factory L.map(id: String, options?: Map options) +// Instantiates a map object given the DOM ID of a `
` element +// and optionally an object literal with `Map options`. +// +// @alternative +// @factory L.map(el: HTMLElement, options?: Map options) +// Instantiates a map object given an instance of a `
` HTML element +// and optionally an object literal with `Map options`. +function createMap(id, options) { + return new Map(id, options); +} + +/* + * @class Control + * @aka L.Control + * @inherits Class + * + * L.Control is a base class for implementing map controls. Handles positioning. + * All other controls extend from this class. + */ + +var Control = Class.extend({ + // @section + // @aka Control Options + options: { + // @option position: String = 'topright' + // The position of the control (one of the map corners). Possible values are `'topleft'`, + // `'topright'`, `'bottomleft'` or `'bottomright'` + position: 'topright' + }, + + initialize: function (options) { + setOptions(this, options); + }, + + /* @section + * Classes extending L.Control will inherit the following methods: + * + * @method getPosition: string + * Returns the position of the control. + */ + getPosition: function () { + return this.options.position; + }, + + // @method setPosition(position: string): this + // Sets the position of the control. + setPosition: function (position) { + var map = this._map; + + if (map) { + map.removeControl(this); + } + + this.options.position = position; + + if (map) { + map.addControl(this); + } + + return this; + }, + + // @method getContainer: HTMLElement + // Returns the HTMLElement that contains the control. + getContainer: function () { + return this._container; + }, + + // @method addTo(map: Map): this + // Adds the control to the given map. + addTo: function (map) { + this.remove(); + this._map = map; + + var container = this._container = this.onAdd(map), + pos = this.getPosition(), + corner = map._controlCorners[pos]; + + addClass(container, 'leaflet-control'); + + if (pos.indexOf('bottom') !== -1) { + corner.insertBefore(container, corner.firstChild); + } else { + corner.appendChild(container); + } + + this._map.on('unload', this.remove, this); + + return this; + }, + + // @method remove: this + // Removes the control from the map it is currently active on. + remove: function () { + if (!this._map) { + return this; + } + + remove(this._container); + + if (this.onRemove) { + this.onRemove(this._map); + } + + this._map.off('unload', this.remove, this); + this._map = null; + + return this; + }, + + _refocusOnMap: function (e) { + // if map exists and event is not a keyboard event + if (this._map && e && e.screenX > 0 && e.screenY > 0) { + this._map.getContainer().focus(); + } + } +}); + +var control = function (options) { + return new Control(options); +}; + +/* @section Extension methods + * @uninheritable + * + * Every control should extend from `L.Control` and (re-)implement the following methods. + * + * @method onAdd(map: Map): HTMLElement + * Should return the container DOM element for the control and add listeners on relevant map events. Called on [`control.addTo(map)`](#control-addTo). + * + * @method onRemove(map: Map) + * Optional method. Should contain all clean up code that removes the listeners previously added in [`onAdd`](#control-onadd). Called on [`control.remove()`](#control-remove). + */ + +/* @namespace Map + * @section Methods for Layers and Controls + */ +Map.include({ + // @method addControl(control: Control): this + // Adds the given control to the map + addControl: function (control) { + control.addTo(this); + return this; + }, + + // @method removeControl(control: Control): this + // Removes the given control from the map + removeControl: function (control) { + control.remove(); + return this; + }, + + _initControlPos: function () { + var corners = this._controlCorners = {}, + l = 'leaflet-', + container = this._controlContainer = + create$1('div', l + 'control-container', this._container); + + function createCorner(vSide, hSide) { + var className = l + vSide + ' ' + l + hSide; + + corners[vSide + hSide] = create$1('div', className, container); + } + + createCorner('top', 'left'); + createCorner('top', 'right'); + createCorner('bottom', 'left'); + createCorner('bottom', 'right'); + }, + + _clearControlPos: function () { + for (var i in this._controlCorners) { + remove(this._controlCorners[i]); + } + remove(this._controlContainer); + delete this._controlCorners; + delete this._controlContainer; + } +}); + +/* + * @class Control.Layers + * @aka L.Control.Layers + * @inherits Control + * + * The layers control gives users the ability to switch between different base layers and switch overlays on/off (check out the [detailed example](https://leafletjs.com/examples/layers-control/)). Extends `Control`. + * + * @example + * + * ```js + * var baseLayers = { + * "Mapbox": mapbox, + * "OpenStreetMap": osm + * }; + * + * var overlays = { + * "Marker": marker, + * "Roads": roadsLayer + * }; + * + * L.control.layers(baseLayers, overlays).addTo(map); + * ``` + * + * The `baseLayers` and `overlays` parameters are object literals with layer names as keys and `Layer` objects as values: + * + * ```js + * { + * "": layer1, + * "": layer2 + * } + * ``` + * + * The layer names can contain HTML, which allows you to add additional styling to the items: + * + * ```js + * {" My Layer": myLayer} + * ``` + */ + +var Layers = Control.extend({ + // @section + // @aka Control.Layers options + options: { + // @option collapsed: Boolean = true + // If `true`, the control will be collapsed into an icon and expanded on mouse hover, touch, or keyboard activation. + collapsed: true, + position: 'topright', + + // @option autoZIndex: Boolean = true + // If `true`, the control will assign zIndexes in increasing order to all of its layers so that the order is preserved when switching them on/off. + autoZIndex: true, + + // @option hideSingleBase: Boolean = false + // If `true`, the base layers in the control will be hidden when there is only one. + hideSingleBase: false, + + // @option sortLayers: Boolean = false + // Whether to sort the layers. When `false`, layers will keep the order + // in which they were added to the control. + sortLayers: false, + + // @option sortFunction: Function = * + // A [compare function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) + // that will be used for sorting the layers, when `sortLayers` is `true`. + // The function receives both the `L.Layer` instances and their names, as in + // `sortFunction(layerA, layerB, nameA, nameB)`. + // By default, it sorts layers alphabetically by their name. + sortFunction: function (layerA, layerB, nameA, nameB) { + return nameA < nameB ? -1 : (nameB < nameA ? 1 : 0); + } + }, + + initialize: function (baseLayers, overlays, options) { + setOptions(this, options); + + this._layerControlInputs = []; + this._layers = []; + this._lastZIndex = 0; + this._handlingClick = false; + + for (var i in baseLayers) { + this._addLayer(baseLayers[i], i); + } + + for (i in overlays) { + this._addLayer(overlays[i], i, true); + } + }, + + onAdd: function (map) { + this._initLayout(); + this._update(); + + this._map = map; + map.on('zoomend', this._checkDisabledLayers, this); + + for (var i = 0; i < this._layers.length; i++) { + this._layers[i].layer.on('add remove', this._onLayerChange, this); + } + + return this._container; + }, + + addTo: function (map) { + Control.prototype.addTo.call(this, map); + // Trigger expand after Layers Control has been inserted into DOM so that is now has an actual height. + return this._expandIfNotCollapsed(); + }, + + onRemove: function () { + this._map.off('zoomend', this._checkDisabledLayers, this); + + for (var i = 0; i < this._layers.length; i++) { + this._layers[i].layer.off('add remove', this._onLayerChange, this); + } + }, + + // @method addBaseLayer(layer: Layer, name: String): this + // Adds a base layer (radio button entry) with the given name to the control. + addBaseLayer: function (layer, name) { + this._addLayer(layer, name); + return (this._map) ? this._update() : this; + }, + + // @method addOverlay(layer: Layer, name: String): this + // Adds an overlay (checkbox entry) with the given name to the control. + addOverlay: function (layer, name) { + this._addLayer(layer, name, true); + return (this._map) ? this._update() : this; + }, + + // @method removeLayer(layer: Layer): this + // Remove the given layer from the control. + removeLayer: function (layer) { + layer.off('add remove', this._onLayerChange, this); + + var obj = this._getLayer(stamp(layer)); + if (obj) { + this._layers.splice(this._layers.indexOf(obj), 1); + } + return (this._map) ? this._update() : this; + }, + + // @method expand(): this + // Expand the control container if collapsed. + expand: function () { + addClass(this._container, 'leaflet-control-layers-expanded'); + this._section.style.height = null; + var acceptableHeight = this._map.getSize().y - (this._container.offsetTop + 50); + if (acceptableHeight < this._section.clientHeight) { + addClass(this._section, 'leaflet-control-layers-scrollbar'); + this._section.style.height = acceptableHeight + 'px'; + } else { + removeClass(this._section, 'leaflet-control-layers-scrollbar'); + } + this._checkDisabledLayers(); + return this; + }, + + // @method collapse(): this + // Collapse the control container if expanded. + collapse: function () { + removeClass(this._container, 'leaflet-control-layers-expanded'); + return this; + }, + + _initLayout: function () { + var className = 'leaflet-control-layers', + container = this._container = create$1('div', className), + collapsed = this.options.collapsed; + + // makes this work on IE touch devices by stopping it from firing a mouseout event when the touch is released + container.setAttribute('aria-haspopup', true); + + disableClickPropagation(container); + disableScrollPropagation(container); + + var section = this._section = create$1('section', className + '-list'); + + if (collapsed) { + this._map.on('click', this.collapse, this); + + on(container, { + mouseenter: function () { + on(section, 'click', preventDefault); + this.expand(); + setTimeout(function () { + off(section, 'click', preventDefault); + }); + }, + mouseleave: this.collapse + }, this); + } + + var link = this._layersLink = create$1('a', className + '-toggle', container); + link.href = '#'; + link.title = 'Layers'; + link.setAttribute('role', 'button'); + + on(link, 'click', preventDefault); // prevent link function + on(link, 'focus', this.expand, this); + + if (!collapsed) { + this.expand(); + } + + this._baseLayersList = create$1('div', className + '-base', section); + this._separator = create$1('div', className + '-separator', section); + this._overlaysList = create$1('div', className + '-overlays', section); + + container.appendChild(section); + }, + + _getLayer: function (id) { + for (var i = 0; i < this._layers.length; i++) { + + if (this._layers[i] && stamp(this._layers[i].layer) === id) { + return this._layers[i]; + } + } + }, + + _addLayer: function (layer, name, overlay) { + if (this._map) { + layer.on('add remove', this._onLayerChange, this); + } + + this._layers.push({ + layer: layer, + name: name, + overlay: overlay + }); + + if (this.options.sortLayers) { + this._layers.sort(bind(function (a, b) { + return this.options.sortFunction(a.layer, b.layer, a.name, b.name); + }, this)); + } + + if (this.options.autoZIndex && layer.setZIndex) { + this._lastZIndex++; + layer.setZIndex(this._lastZIndex); + } + + this._expandIfNotCollapsed(); + }, + + _update: function () { + if (!this._container) { return this; } + + empty(this._baseLayersList); + empty(this._overlaysList); + + this._layerControlInputs = []; + var baseLayersPresent, overlaysPresent, i, obj, baseLayersCount = 0; + + for (i = 0; i < this._layers.length; i++) { + obj = this._layers[i]; + this._addItem(obj); + overlaysPresent = overlaysPresent || obj.overlay; + baseLayersPresent = baseLayersPresent || !obj.overlay; + baseLayersCount += !obj.overlay ? 1 : 0; + } + + // Hide base layers section if there's only one layer. + if (this.options.hideSingleBase) { + baseLayersPresent = baseLayersPresent && baseLayersCount > 1; + this._baseLayersList.style.display = baseLayersPresent ? '' : 'none'; + } + + this._separator.style.display = overlaysPresent && baseLayersPresent ? '' : 'none'; + + return this; + }, + + _onLayerChange: function (e) { + if (!this._handlingClick) { + this._update(); + } + + var obj = this._getLayer(stamp(e.target)); + + // @namespace Map + // @section Layer events + // @event baselayerchange: LayersControlEvent + // Fired when the base layer is changed through the [layers control](#control-layers). + // @event overlayadd: LayersControlEvent + // Fired when an overlay is selected through the [layers control](#control-layers). + // @event overlayremove: LayersControlEvent + // Fired when an overlay is deselected through the [layers control](#control-layers). + // @namespace Control.Layers + var type = obj.overlay ? + (e.type === 'add' ? 'overlayadd' : 'overlayremove') : + (e.type === 'add' ? 'baselayerchange' : null); + + if (type) { + this._map.fire(type, obj); + } + }, + + // IE7 bugs out if you create a radio dynamically, so you have to do it this hacky way (see https://stackoverflow.com/a/119079) + _createRadioElement: function (name, checked) { + + var radioHtml = ''; + + var radioFragment = document.createElement('div'); + radioFragment.innerHTML = radioHtml; + + return radioFragment.firstChild; + }, + + _addItem: function (obj) { + var label = document.createElement('label'), + checked = this._map.hasLayer(obj.layer), + input; + + if (obj.overlay) { + input = document.createElement('input'); + input.type = 'checkbox'; + input.className = 'leaflet-control-layers-selector'; + input.defaultChecked = checked; + } else { + input = this._createRadioElement('leaflet-base-layers_' + stamp(this), checked); + } + + this._layerControlInputs.push(input); + input.layerId = stamp(obj.layer); + + on(input, 'click', this._onInputClick, this); + + var name = document.createElement('span'); + name.innerHTML = ' ' + obj.name; + + // Helps from preventing layer control flicker when checkboxes are disabled + // https://github.com/Leaflet/Leaflet/issues/2771 + var holder = document.createElement('span'); + + label.appendChild(holder); + holder.appendChild(input); + holder.appendChild(name); + + var container = obj.overlay ? this._overlaysList : this._baseLayersList; + container.appendChild(label); + + this._checkDisabledLayers(); + return label; + }, + + _onInputClick: function () { + var inputs = this._layerControlInputs, + input, layer; + var addedLayers = [], + removedLayers = []; + + this._handlingClick = true; + + for (var i = inputs.length - 1; i >= 0; i--) { + input = inputs[i]; + layer = this._getLayer(input.layerId).layer; + + if (input.checked) { + addedLayers.push(layer); + } else if (!input.checked) { + removedLayers.push(layer); + } + } + + // Bugfix issue 2318: Should remove all old layers before readding new ones + for (i = 0; i < removedLayers.length; i++) { + if (this._map.hasLayer(removedLayers[i])) { + this._map.removeLayer(removedLayers[i]); + } + } + for (i = 0; i < addedLayers.length; i++) { + if (!this._map.hasLayer(addedLayers[i])) { + this._map.addLayer(addedLayers[i]); + } + } + + this._handlingClick = false; + + this._refocusOnMap(); + }, + + _checkDisabledLayers: function () { + var inputs = this._layerControlInputs, + input, + layer, + zoom = this._map.getZoom(); + + for (var i = inputs.length - 1; i >= 0; i--) { + input = inputs[i]; + layer = this._getLayer(input.layerId).layer; + input.disabled = (layer.options.minZoom !== undefined && zoom < layer.options.minZoom) || + (layer.options.maxZoom !== undefined && zoom > layer.options.maxZoom); + + } + }, + + _expandIfNotCollapsed: function () { + if (this._map && !this.options.collapsed) { + this.expand(); + } + return this; + } + +}); + + +// @factory L.control.layers(baselayers?: Object, overlays?: Object, options?: Control.Layers options) +// Creates a layers control with the given layers. Base layers will be switched with radio buttons, while overlays will be switched with checkboxes. Note that all base layers should be passed in the base layers object, but only one should be added to the map during map instantiation. +var layers = function (baseLayers, overlays, options) { + return new Layers(baseLayers, overlays, options); +}; + +/* + * @class Control.Zoom + * @aka L.Control.Zoom + * @inherits Control + * + * A basic zoom control with two buttons (zoom in and zoom out). It is put on the map by default unless you set its [`zoomControl` option](#map-zoomcontrol) to `false`. Extends `Control`. + */ + +var Zoom = Control.extend({ + // @section + // @aka Control.Zoom options + options: { + position: 'topleft', + + // @option zoomInText: String = '' + // The text set on the 'zoom in' button. + zoomInText: '', + + // @option zoomInTitle: String = 'Zoom in' + // The title set on the 'zoom in' button. + zoomInTitle: 'Zoom in', + + // @option zoomOutText: String = '' + // The text set on the 'zoom out' button. + zoomOutText: '', + + // @option zoomOutTitle: String = 'Zoom out' + // The title set on the 'zoom out' button. + zoomOutTitle: 'Zoom out' + }, + + onAdd: function (map) { + var zoomName = 'leaflet-control-zoom', + container = create$1('div', zoomName + ' leaflet-bar'), + options = this.options; + + this._zoomInButton = this._createButton(options.zoomInText, options.zoomInTitle, + zoomName + '-in', container, this._zoomIn); + this._zoomOutButton = this._createButton(options.zoomOutText, options.zoomOutTitle, + zoomName + '-out', container, this._zoomOut); + + this._updateDisabled(); + map.on('zoomend zoomlevelschange', this._updateDisabled, this); + + return container; + }, + + onRemove: function (map) { + map.off('zoomend zoomlevelschange', this._updateDisabled, this); + }, + + disable: function () { + this._disabled = true; + this._updateDisabled(); + return this; + }, + + enable: function () { + this._disabled = false; + this._updateDisabled(); + return this; + }, + + _zoomIn: function (e) { + if (!this._disabled && this._map._zoom < this._map.getMaxZoom()) { + this._map.zoomIn(this._map.options.zoomDelta * (e.shiftKey ? 3 : 1)); + } + }, + + _zoomOut: function (e) { + if (!this._disabled && this._map._zoom > this._map.getMinZoom()) { + this._map.zoomOut(this._map.options.zoomDelta * (e.shiftKey ? 3 : 1)); + } + }, + + _createButton: function (html, title, className, container, fn) { + var link = create$1('a', className, container); + link.innerHTML = html; + link.href = '#'; + link.title = title; + + /* + * Will force screen readers like VoiceOver to read this as "Zoom in - button" + */ + link.setAttribute('role', 'button'); + link.setAttribute('aria-label', title); + + disableClickPropagation(link); + on(link, 'click', stop); + on(link, 'click', fn, this); + on(link, 'click', this._refocusOnMap, this); + + return link; + }, + + _updateDisabled: function () { + var map = this._map, + className = 'leaflet-disabled'; + + removeClass(this._zoomInButton, className); + removeClass(this._zoomOutButton, className); + this._zoomInButton.setAttribute('aria-disabled', 'false'); + this._zoomOutButton.setAttribute('aria-disabled', 'false'); + + if (this._disabled || map._zoom === map.getMinZoom()) { + addClass(this._zoomOutButton, className); + this._zoomOutButton.setAttribute('aria-disabled', 'true'); + } + if (this._disabled || map._zoom === map.getMaxZoom()) { + addClass(this._zoomInButton, className); + this._zoomInButton.setAttribute('aria-disabled', 'true'); + } + } +}); + +// @namespace Map +// @section Control options +// @option zoomControl: Boolean = true +// Whether a [zoom control](#control-zoom) is added to the map by default. +Map.mergeOptions({ + zoomControl: true +}); + +Map.addInitHook(function () { + if (this.options.zoomControl) { + // @section Controls + // @property zoomControl: Control.Zoom + // The default zoom control (only available if the + // [`zoomControl` option](#map-zoomcontrol) was `true` when creating the map). + this.zoomControl = new Zoom(); + this.addControl(this.zoomControl); + } +}); + +// @namespace Control.Zoom +// @factory L.control.zoom(options: Control.Zoom options) +// Creates a zoom control +var zoom = function (options) { + return new Zoom(options); +}; + +/* + * @class Control.Scale + * @aka L.Control.Scale + * @inherits Control + * + * A simple scale control that shows the scale of the current center of screen in metric (m/km) and imperial (mi/ft) systems. Extends `Control`. + * + * @example + * + * ```js + * L.control.scale().addTo(map); + * ``` + */ + +var Scale = Control.extend({ + // @section + // @aka Control.Scale options + options: { + position: 'bottomleft', + + // @option maxWidth: Number = 100 + // Maximum width of the control in pixels. The width is set dynamically to show round values (e.g. 100, 200, 500). + maxWidth: 100, + + // @option metric: Boolean = True + // Whether to show the metric scale line (m/km). + metric: true, + + // @option imperial: Boolean = True + // Whether to show the imperial scale line (mi/ft). + imperial: true + + // @option updateWhenIdle: Boolean = false + // If `true`, the control is updated on [`moveend`](#map-moveend), otherwise it's always up-to-date (updated on [`move`](#map-move)). + }, + + onAdd: function (map) { + var className = 'leaflet-control-scale', + container = create$1('div', className), + options = this.options; + + this._addScales(options, className + '-line', container); + + map.on(options.updateWhenIdle ? 'moveend' : 'move', this._update, this); + map.whenReady(this._update, this); + + return container; + }, + + onRemove: function (map) { + map.off(this.options.updateWhenIdle ? 'moveend' : 'move', this._update, this); + }, + + _addScales: function (options, className, container) { + if (options.metric) { + this._mScale = create$1('div', className, container); + } + if (options.imperial) { + this._iScale = create$1('div', className, container); + } + }, + + _update: function () { + var map = this._map, + y = map.getSize().y / 2; + + var maxMeters = map.distance( + map.containerPointToLatLng([0, y]), + map.containerPointToLatLng([this.options.maxWidth, y])); + + this._updateScales(maxMeters); + }, + + _updateScales: function (maxMeters) { + if (this.options.metric && maxMeters) { + this._updateMetric(maxMeters); + } + if (this.options.imperial && maxMeters) { + this._updateImperial(maxMeters); + } + }, + + _updateMetric: function (maxMeters) { + var meters = this._getRoundNum(maxMeters), + label = meters < 1000 ? meters + ' m' : (meters / 1000) + ' km'; + + this._updateScale(this._mScale, label, meters / maxMeters); + }, + + _updateImperial: function (maxMeters) { + var maxFeet = maxMeters * 3.2808399, + maxMiles, miles, feet; + + if (maxFeet > 5280) { + maxMiles = maxFeet / 5280; + miles = this._getRoundNum(maxMiles); + this._updateScale(this._iScale, miles + ' mi', miles / maxMiles); + + } else { + feet = this._getRoundNum(maxFeet); + this._updateScale(this._iScale, feet + ' ft', feet / maxFeet); + } + }, + + _updateScale: function (scale, text, ratio) { + scale.style.width = Math.round(this.options.maxWidth * ratio) + 'px'; + scale.innerHTML = text; + }, + + _getRoundNum: function (num) { + var pow10 = Math.pow(10, (Math.floor(num) + '').length - 1), + d = num / pow10; + + d = d >= 10 ? 10 : + d >= 5 ? 5 : + d >= 3 ? 3 : + d >= 2 ? 2 : 1; + + return pow10 * d; + } +}); + + +// @factory L.control.scale(options?: Control.Scale options) +// Creates an scale control with the given options. +var scale = function (options) { + return new Scale(options); +}; + +var ukrainianFlag = ''; + + +/* + * @class Control.Attribution + * @aka L.Control.Attribution + * @inherits Control + * + * The attribution control allows you to display attribution data in a small text box on a map. It is put on the map by default unless you set its [`attributionControl` option](#map-attributioncontrol) to `false`, and it fetches attribution texts from layers with the [`getAttribution` method](#layer-getattribution) automatically. Extends Control. + */ + +var Attribution = Control.extend({ + // @section + // @aka Control.Attribution options + options: { + position: 'bottomright', + + // @option prefix: String|false = 'Leaflet' + // The HTML text shown before the attributions. Pass `false` to disable. + prefix: '' + (Browser.inlineSvg ? ukrainianFlag + ' ' : '') + 'Leaflet' + }, + + initialize: function (options) { + setOptions(this, options); + + this._attributions = {}; + }, + + onAdd: function (map) { + map.attributionControl = this; + this._container = create$1('div', 'leaflet-control-attribution'); + disableClickPropagation(this._container); + + // TODO ugly, refactor + for (var i in map._layers) { + if (map._layers[i].getAttribution) { + this.addAttribution(map._layers[i].getAttribution()); + } + } + + this._update(); + + map.on('layeradd', this._addAttribution, this); + + return this._container; + }, + + onRemove: function (map) { + map.off('layeradd', this._addAttribution, this); + }, + + _addAttribution: function (ev) { + if (ev.layer.getAttribution) { + this.addAttribution(ev.layer.getAttribution()); + ev.layer.once('remove', function () { + this.removeAttribution(ev.layer.getAttribution()); + }, this); + } + }, + + // @method setPrefix(prefix: String|false): this + // The HTML text shown before the attributions. Pass `false` to disable. + setPrefix: function (prefix) { + this.options.prefix = prefix; + this._update(); + return this; + }, + + // @method addAttribution(text: String): this + // Adds an attribution text (e.g. `'Vector data © Mapbox'`). + addAttribution: function (text) { + if (!text) { return this; } + + if (!this._attributions[text]) { + this._attributions[text] = 0; + } + this._attributions[text]++; + + this._update(); + + return this; + }, + + // @method removeAttribution(text: String): this + // Removes an attribution text. + removeAttribution: function (text) { + if (!text) { return this; } + + if (this._attributions[text]) { + this._attributions[text]--; + this._update(); + } + + return this; + }, + + _update: function () { + if (!this._map) { return; } + + var attribs = []; + + for (var i in this._attributions) { + if (this._attributions[i]) { + attribs.push(i); + } + } + + var prefixAndAttribs = []; + + if (this.options.prefix) { + prefixAndAttribs.push(this.options.prefix); + } + if (attribs.length) { + prefixAndAttribs.push(attribs.join(', ')); + } + + this._container.innerHTML = prefixAndAttribs.join(' '); + } +}); + +// @namespace Map +// @section Control options +// @option attributionControl: Boolean = true +// Whether a [attribution control](#control-attribution) is added to the map by default. +Map.mergeOptions({ + attributionControl: true +}); + +Map.addInitHook(function () { + if (this.options.attributionControl) { + new Attribution().addTo(this); + } +}); + +// @namespace Control.Attribution +// @factory L.control.attribution(options: Control.Attribution options) +// Creates an attribution control. +var attribution = function (options) { + return new Attribution(options); +}; + +Control.Layers = Layers; +Control.Zoom = Zoom; +Control.Scale = Scale; +Control.Attribution = Attribution; + +control.layers = layers; +control.zoom = zoom; +control.scale = scale; +control.attribution = attribution; + +/* + L.Handler is a base class for handler classes that are used internally to inject + interaction features like dragging to classes like Map and Marker. +*/ + +// @class Handler +// @aka L.Handler +// Abstract class for map interaction handlers + +var Handler = Class.extend({ + initialize: function (map) { + this._map = map; + }, + + // @method enable(): this + // Enables the handler + enable: function () { + if (this._enabled) { return this; } + + this._enabled = true; + this.addHooks(); + return this; + }, + + // @method disable(): this + // Disables the handler + disable: function () { + if (!this._enabled) { return this; } + + this._enabled = false; + this.removeHooks(); + return this; + }, + + // @method enabled(): Boolean + // Returns `true` if the handler is enabled + enabled: function () { + return !!this._enabled; + } + + // @section Extension methods + // Classes inheriting from `Handler` must implement the two following methods: + // @method addHooks() + // Called when the handler is enabled, should add event hooks. + // @method removeHooks() + // Called when the handler is disabled, should remove the event hooks added previously. +}); + +// @section There is static function which can be called without instantiating L.Handler: +// @function addTo(map: Map, name: String): this +// Adds a new Handler to the given map with the given name. +Handler.addTo = function (map, name) { + map.addHandler(name, this); + return this; +}; + +var Mixin = {Events: Events}; + +/* + * @class Draggable + * @aka L.Draggable + * @inherits Evented + * + * A class for making DOM elements draggable (including touch support). + * Used internally for map and marker dragging. Only works for elements + * that were positioned with [`L.DomUtil.setPosition`](#domutil-setposition). + * + * @example + * ```js + * var draggable = new L.Draggable(elementToDrag); + * draggable.enable(); + * ``` + */ + +var START = Browser.touch ? 'touchstart mousedown' : 'mousedown'; + +var Draggable = Evented.extend({ + + options: { + // @section + // @aka Draggable options + // @option clickTolerance: Number = 3 + // The max number of pixels a user can shift the mouse pointer during a click + // for it to be considered a valid click (as opposed to a mouse drag). + clickTolerance: 3 + }, + + // @constructor L.Draggable(el: HTMLElement, dragHandle?: HTMLElement, preventOutline?: Boolean, options?: Draggable options) + // Creates a `Draggable` object for moving `el` when you start dragging the `dragHandle` element (equals `el` itself by default). + initialize: function (element, dragStartTarget, preventOutline, options) { + setOptions(this, options); + + this._element = element; + this._dragStartTarget = dragStartTarget || element; + this._preventOutline = preventOutline; + }, + + // @method enable() + // Enables the dragging ability + enable: function () { + if (this._enabled) { return; } + + on(this._dragStartTarget, START, this._onDown, this); + + this._enabled = true; + }, + + // @method disable() + // Disables the dragging ability + disable: function () { + if (!this._enabled) { return; } + + // If we're currently dragging this draggable, + // disabling it counts as first ending the drag. + if (Draggable._dragging === this) { + this.finishDrag(true); + } + + off(this._dragStartTarget, START, this._onDown, this); + + this._enabled = false; + this._moved = false; + }, + + _onDown: function (e) { + // Ignore the event if disabled; this happens in IE11 + // under some circumstances, see #3666. + if (!this._enabled) { return; } + + this._moved = false; + + if (hasClass(this._element, 'leaflet-zoom-anim')) { return; } + + if (e.touches && e.touches.length !== 1) { + // Finish dragging to avoid conflict with touchZoom + if (Draggable._dragging === this) { + this.finishDrag(); + } + return; + } + + if (Draggable._dragging || e.shiftKey || ((e.which !== 1) && (e.button !== 1) && !e.touches)) { return; } + Draggable._dragging = this; // Prevent dragging multiple objects at once. + + if (this._preventOutline) { + preventOutline(this._element); + } + + disableImageDrag(); + disableTextSelection(); + + if (this._moving) { return; } + + // @event down: Event + // Fired when a drag is about to start. + this.fire('down'); + + var first = e.touches ? e.touches[0] : e, + sizedParent = getSizedParentNode(this._element); + + this._startPoint = new Point(first.clientX, first.clientY); + this._startPos = getPosition(this._element); + + // Cache the scale, so that we can continuously compensate for it during drag (_onMove). + this._parentScale = getScale(sizedParent); + + var mouseevent = e.type === 'mousedown'; + on(document, mouseevent ? 'mousemove' : 'touchmove', this._onMove, this); + on(document, mouseevent ? 'mouseup' : 'touchend touchcancel', this._onUp, this); + }, + + _onMove: function (e) { + // Ignore the event if disabled; this happens in IE11 + // under some circumstances, see #3666. + if (!this._enabled) { return; } + + if (e.touches && e.touches.length > 1) { + this._moved = true; + return; + } + + var first = (e.touches && e.touches.length === 1 ? e.touches[0] : e), + offset = new Point(first.clientX, first.clientY)._subtract(this._startPoint); + + if (!offset.x && !offset.y) { return; } + if (Math.abs(offset.x) + Math.abs(offset.y) < this.options.clickTolerance) { return; } + + // We assume that the parent container's position, border and scale do not change for the duration of the drag. + // Therefore there is no need to account for the position and border (they are eliminated by the subtraction) + // and we can use the cached value for the scale. + offset.x /= this._parentScale.x; + offset.y /= this._parentScale.y; + + preventDefault(e); + + if (!this._moved) { + // @event dragstart: Event + // Fired when a drag starts + this.fire('dragstart'); + + this._moved = true; + + addClass(document.body, 'leaflet-dragging'); + + this._lastTarget = e.target || e.srcElement; + // IE and Edge do not give the element, so fetch it + // if necessary + if (window.SVGElementInstance && this._lastTarget instanceof window.SVGElementInstance) { + this._lastTarget = this._lastTarget.correspondingUseElement; + } + addClass(this._lastTarget, 'leaflet-drag-target'); + } + + this._newPos = this._startPos.add(offset); + this._moving = true; + + this._lastEvent = e; + this._updatePosition(); + }, + + _updatePosition: function () { + var e = {originalEvent: this._lastEvent}; + + // @event predrag: Event + // Fired continuously during dragging *before* each corresponding + // update of the element's position. + this.fire('predrag', e); + setPosition(this._element, this._newPos); + + // @event drag: Event + // Fired continuously during dragging. + this.fire('drag', e); + }, + + _onUp: function () { + // Ignore the event if disabled; this happens in IE11 + // under some circumstances, see #3666. + if (!this._enabled) { return; } + this.finishDrag(); + }, + + finishDrag: function (noInertia) { + removeClass(document.body, 'leaflet-dragging'); + + if (this._lastTarget) { + removeClass(this._lastTarget, 'leaflet-drag-target'); + this._lastTarget = null; + } + + off(document, 'mousemove touchmove', this._onMove, this); + off(document, 'mouseup touchend touchcancel', this._onUp, this); + + enableImageDrag(); + enableTextSelection(); + + if (this._moved && this._moving) { + + // @event dragend: DragEndEvent + // Fired when the drag ends. + this.fire('dragend', { + noInertia: noInertia, + distance: this._newPos.distanceTo(this._startPos) + }); + } + + this._moving = false; + Draggable._dragging = false; + } + +}); + +/* + * @namespace LineUtil + * + * Various utility functions for polyline points processing, used by Leaflet internally to make polylines lightning-fast. + */ + +// Simplify polyline with vertex reduction and Douglas-Peucker simplification. +// Improves rendering performance dramatically by lessening the number of points to draw. + +// @function simplify(points: Point[], tolerance: Number): Point[] +// Dramatically reduces the number of points in a polyline while retaining +// its shape and returns a new array of simplified points, using the +// [Ramer-Douglas-Peucker algorithm](https://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm). +// Used for a huge performance boost when processing/displaying Leaflet polylines for +// each zoom level and also reducing visual noise. tolerance affects the amount of +// simplification (lesser value means higher quality but slower and with more points). +// Also released as a separated micro-library [Simplify.js](https://mourner.github.io/simplify-js/). +function simplify(points, tolerance) { + if (!tolerance || !points.length) { + return points.slice(); + } + + var sqTolerance = tolerance * tolerance; + + // stage 1: vertex reduction + points = _reducePoints(points, sqTolerance); + + // stage 2: Douglas-Peucker simplification + points = _simplifyDP(points, sqTolerance); + + return points; +} + +// @function pointToSegmentDistance(p: Point, p1: Point, p2: Point): Number +// Returns the distance between point `p` and segment `p1` to `p2`. +function pointToSegmentDistance(p, p1, p2) { + return Math.sqrt(_sqClosestPointOnSegment(p, p1, p2, true)); +} + +// @function closestPointOnSegment(p: Point, p1: Point, p2: Point): Number +// Returns the closest point from a point `p` on a segment `p1` to `p2`. +function closestPointOnSegment(p, p1, p2) { + return _sqClosestPointOnSegment(p, p1, p2); +} + +// Ramer-Douglas-Peucker simplification, see https://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm +function _simplifyDP(points, sqTolerance) { + + var len = points.length, + ArrayConstructor = typeof Uint8Array !== undefined + '' ? Uint8Array : Array, + markers = new ArrayConstructor(len); + + markers[0] = markers[len - 1] = 1; + + _simplifyDPStep(points, markers, sqTolerance, 0, len - 1); + + var i, + newPoints = []; + + for (i = 0; i < len; i++) { + if (markers[i]) { + newPoints.push(points[i]); + } + } + + return newPoints; +} + +function _simplifyDPStep(points, markers, sqTolerance, first, last) { + + var maxSqDist = 0, + index, i, sqDist; + + for (i = first + 1; i <= last - 1; i++) { + sqDist = _sqClosestPointOnSegment(points[i], points[first], points[last], true); + + if (sqDist > maxSqDist) { + index = i; + maxSqDist = sqDist; + } + } + + if (maxSqDist > sqTolerance) { + markers[index] = 1; + + _simplifyDPStep(points, markers, sqTolerance, first, index); + _simplifyDPStep(points, markers, sqTolerance, index, last); + } +} + +// reduce points that are too close to each other to a single point +function _reducePoints(points, sqTolerance) { + var reducedPoints = [points[0]]; + + for (var i = 1, prev = 0, len = points.length; i < len; i++) { + if (_sqDist(points[i], points[prev]) > sqTolerance) { + reducedPoints.push(points[i]); + prev = i; + } + } + if (prev < len - 1) { + reducedPoints.push(points[len - 1]); + } + return reducedPoints; +} + +var _lastCode; + +// @function clipSegment(a: Point, b: Point, bounds: Bounds, useLastCode?: Boolean, round?: Boolean): Point[]|Boolean +// Clips the segment a to b by rectangular bounds with the +// [Cohen-Sutherland algorithm](https://en.wikipedia.org/wiki/Cohen%E2%80%93Sutherland_algorithm) +// (modifying the segment points directly!). Used by Leaflet to only show polyline +// points that are on the screen or near, increasing performance. +function clipSegment(a, b, bounds, useLastCode, round) { + var codeA = useLastCode ? _lastCode : _getBitCode(a, bounds), + codeB = _getBitCode(b, bounds), + + codeOut, p, newCode; + + // save 2nd code to avoid calculating it on the next segment + _lastCode = codeB; + + while (true) { + // if a,b is inside the clip window (trivial accept) + if (!(codeA | codeB)) { + return [a, b]; + } + + // if a,b is outside the clip window (trivial reject) + if (codeA & codeB) { + return false; + } + + // other cases + codeOut = codeA || codeB; + p = _getEdgeIntersection(a, b, codeOut, bounds, round); + newCode = _getBitCode(p, bounds); + + if (codeOut === codeA) { + a = p; + codeA = newCode; + } else { + b = p; + codeB = newCode; + } + } +} + +function _getEdgeIntersection(a, b, code, bounds, round) { + var dx = b.x - a.x, + dy = b.y - a.y, + min = bounds.min, + max = bounds.max, + x, y; + + if (code & 8) { // top + x = a.x + dx * (max.y - a.y) / dy; + y = max.y; + + } else if (code & 4) { // bottom + x = a.x + dx * (min.y - a.y) / dy; + y = min.y; + + } else if (code & 2) { // right + x = max.x; + y = a.y + dy * (max.x - a.x) / dx; + + } else if (code & 1) { // left + x = min.x; + y = a.y + dy * (min.x - a.x) / dx; + } + + return new Point(x, y, round); +} + +function _getBitCode(p, bounds) { + var code = 0; + + if (p.x < bounds.min.x) { // left + code |= 1; + } else if (p.x > bounds.max.x) { // right + code |= 2; + } + + if (p.y < bounds.min.y) { // bottom + code |= 4; + } else if (p.y > bounds.max.y) { // top + code |= 8; + } + + return code; +} + +// square distance (to avoid unnecessary Math.sqrt calls) +function _sqDist(p1, p2) { + var dx = p2.x - p1.x, + dy = p2.y - p1.y; + return dx * dx + dy * dy; +} + +// return closest point on segment or distance to that point +function _sqClosestPointOnSegment(p, p1, p2, sqDist) { + var x = p1.x, + y = p1.y, + dx = p2.x - x, + dy = p2.y - y, + dot = dx * dx + dy * dy, + t; + + if (dot > 0) { + t = ((p.x - x) * dx + (p.y - y) * dy) / dot; + + if (t > 1) { + x = p2.x; + y = p2.y; + } else if (t > 0) { + x += dx * t; + y += dy * t; + } + } + + dx = p.x - x; + dy = p.y - y; + + return sqDist ? dx * dx + dy * dy : new Point(x, y); +} + + +// @function isFlat(latlngs: LatLng[]): Boolean +// Returns true if `latlngs` is a flat array, false is nested. +function isFlat(latlngs) { + return !isArray(latlngs[0]) || (typeof latlngs[0][0] !== 'object' && typeof latlngs[0][0] !== 'undefined'); +} + +function _flat(latlngs) { + console.warn('Deprecated use of _flat, please use L.LineUtil.isFlat instead.'); + return isFlat(latlngs); +} + +var LineUtil = { + __proto__: null, + simplify: simplify, + pointToSegmentDistance: pointToSegmentDistance, + closestPointOnSegment: closestPointOnSegment, + clipSegment: clipSegment, + _getEdgeIntersection: _getEdgeIntersection, + _getBitCode: _getBitCode, + _sqClosestPointOnSegment: _sqClosestPointOnSegment, + isFlat: isFlat, + _flat: _flat +}; + +/* + * @namespace PolyUtil + * Various utility functions for polygon geometries. + */ + +/* @function clipPolygon(points: Point[], bounds: Bounds, round?: Boolean): Point[] + * Clips the polygon geometry defined by the given `points` by the given bounds (using the [Sutherland-Hodgman algorithm](https://en.wikipedia.org/wiki/Sutherland%E2%80%93Hodgman_algorithm)). + * Used by Leaflet to only show polygon points that are on the screen or near, increasing + * performance. Note that polygon points needs different algorithm for clipping + * than polyline, so there's a separate method for it. + */ +function clipPolygon(points, bounds, round) { + var clippedPoints, + edges = [1, 4, 2, 8], + i, j, k, + a, b, + len, edge, p; + + for (i = 0, len = points.length; i < len; i++) { + points[i]._code = _getBitCode(points[i], bounds); + } + + // for each edge (left, bottom, right, top) + for (k = 0; k < 4; k++) { + edge = edges[k]; + clippedPoints = []; + + for (i = 0, len = points.length, j = len - 1; i < len; j = i++) { + a = points[i]; + b = points[j]; + + // if a is inside the clip window + if (!(a._code & edge)) { + // if b is outside the clip window (a->b goes out of screen) + if (b._code & edge) { + p = _getEdgeIntersection(b, a, edge, bounds, round); + p._code = _getBitCode(p, bounds); + clippedPoints.push(p); + } + clippedPoints.push(a); + + // else if b is inside the clip window (a->b enters the screen) + } else if (!(b._code & edge)) { + p = _getEdgeIntersection(b, a, edge, bounds, round); + p._code = _getBitCode(p, bounds); + clippedPoints.push(p); + } + } + points = clippedPoints; + } + + return points; +} + +var PolyUtil = { + __proto__: null, + clipPolygon: clipPolygon +}; + +/* + * @namespace Projection + * @section + * Leaflet comes with a set of already defined Projections out of the box: + * + * @projection L.Projection.LonLat + * + * Equirectangular, or Plate Carree projection — the most simple projection, + * mostly used by GIS enthusiasts. Directly maps `x` as longitude, and `y` as + * latitude. Also suitable for flat worlds, e.g. game maps. Used by the + * `EPSG:4326` and `Simple` CRS. + */ + +var LonLat = { + project: function (latlng) { + return new Point(latlng.lng, latlng.lat); + }, + + unproject: function (point) { + return new LatLng(point.y, point.x); + }, + + bounds: new Bounds([-180, -90], [180, 90]) +}; + +/* + * @namespace Projection + * @projection L.Projection.Mercator + * + * Elliptical Mercator projection — more complex than Spherical Mercator. Assumes that Earth is an ellipsoid. Used by the EPSG:3395 CRS. + */ + +var Mercator = { + R: 6378137, + R_MINOR: 6356752.314245179, + + bounds: new Bounds([-20037508.34279, -15496570.73972], [20037508.34279, 18764656.23138]), + + project: function (latlng) { + var d = Math.PI / 180, + r = this.R, + y = latlng.lat * d, + tmp = this.R_MINOR / r, + e = Math.sqrt(1 - tmp * tmp), + con = e * Math.sin(y); + + var ts = Math.tan(Math.PI / 4 - y / 2) / Math.pow((1 - con) / (1 + con), e / 2); + y = -r * Math.log(Math.max(ts, 1E-10)); + + return new Point(latlng.lng * d * r, y); + }, + + unproject: function (point) { + var d = 180 / Math.PI, + r = this.R, + tmp = this.R_MINOR / r, + e = Math.sqrt(1 - tmp * tmp), + ts = Math.exp(-point.y / r), + phi = Math.PI / 2 - 2 * Math.atan(ts); + + for (var i = 0, dphi = 0.1, con; i < 15 && Math.abs(dphi) > 1e-7; i++) { + con = e * Math.sin(phi); + con = Math.pow((1 - con) / (1 + con), e / 2); + dphi = Math.PI / 2 - 2 * Math.atan(ts * con) - phi; + phi += dphi; + } + + return new LatLng(phi * d, point.x * d / r); + } +}; + +/* + * @class Projection + + * An object with methods for projecting geographical coordinates of the world onto + * a flat surface (and back). See [Map projection](https://en.wikipedia.org/wiki/Map_projection). + + * @property bounds: Bounds + * The bounds (specified in CRS units) where the projection is valid + + * @method project(latlng: LatLng): Point + * Projects geographical coordinates into a 2D point. + * Only accepts actual `L.LatLng` instances, not arrays. + + * @method unproject(point: Point): LatLng + * The inverse of `project`. Projects a 2D point into a geographical location. + * Only accepts actual `L.Point` instances, not arrays. + + * Note that the projection instances do not inherit from Leaflet's `Class` object, + * and can't be instantiated. Also, new classes can't inherit from them, + * and methods can't be added to them with the `include` function. + + */ + +var index = { + __proto__: null, + LonLat: LonLat, + Mercator: Mercator, + SphericalMercator: SphericalMercator +}; + +/* + * @namespace CRS + * @crs L.CRS.EPSG3395 + * + * Rarely used by some commercial tile providers. Uses Elliptical Mercator projection. + */ +var EPSG3395 = extend({}, Earth, { + code: 'EPSG:3395', + projection: Mercator, + + transformation: (function () { + var scale = 0.5 / (Math.PI * Mercator.R); + return toTransformation(scale, 0.5, -scale, 0.5); + }()) +}); + +/* + * @namespace CRS + * @crs L.CRS.EPSG4326 + * + * A common CRS among GIS enthusiasts. Uses simple Equirectangular projection. + * + * Leaflet 1.0.x complies with the [TMS coordinate scheme for EPSG:4326](https://wiki.osgeo.org/wiki/Tile_Map_Service_Specification#global-geodetic), + * which is a breaking change from 0.7.x behaviour. If you are using a `TileLayer` + * with this CRS, ensure that there are two 256x256 pixel tiles covering the + * whole earth at zoom level zero, and that the tile coordinate origin is (-180,+90), + * or (-180,-90) for `TileLayer`s with [the `tms` option](#tilelayer-tms) set. + */ + +var EPSG4326 = extend({}, Earth, { + code: 'EPSG:4326', + projection: LonLat, + transformation: toTransformation(1 / 180, 1, -1 / 180, 0.5) +}); + +/* + * @namespace CRS + * @crs L.CRS.Simple + * + * A simple CRS that maps longitude and latitude into `x` and `y` directly. + * May be used for maps of flat surfaces (e.g. game maps). Note that the `y` + * axis should still be inverted (going from bottom to top). `distance()` returns + * simple euclidean distance. + */ + +var Simple = extend({}, CRS, { + projection: LonLat, + transformation: toTransformation(1, 0, -1, 0), + + scale: function (zoom) { + return Math.pow(2, zoom); + }, + + zoom: function (scale) { + return Math.log(scale) / Math.LN2; + }, + + distance: function (latlng1, latlng2) { + var dx = latlng2.lng - latlng1.lng, + dy = latlng2.lat - latlng1.lat; + + return Math.sqrt(dx * dx + dy * dy); + }, + + infinite: true +}); + +CRS.Earth = Earth; +CRS.EPSG3395 = EPSG3395; +CRS.EPSG3857 = EPSG3857; +CRS.EPSG900913 = EPSG900913; +CRS.EPSG4326 = EPSG4326; +CRS.Simple = Simple; + +/* + * @class Layer + * @inherits Evented + * @aka L.Layer + * @aka ILayer + * + * A set of methods from the Layer base class that all Leaflet layers use. + * Inherits all methods, options and events from `L.Evented`. + * + * @example + * + * ```js + * var layer = L.marker(latlng).addTo(map); + * layer.addTo(map); + * layer.remove(); + * ``` + * + * @event add: Event + * Fired after the layer is added to a map + * + * @event remove: Event + * Fired after the layer is removed from a map + */ + + +var Layer = Evented.extend({ + + // Classes extending `L.Layer` will inherit the following options: + options: { + // @option pane: String = 'overlayPane' + // By default the layer will be added to the map's [overlay pane](#map-overlaypane). Overriding this option will cause the layer to be placed on another pane by default. + pane: 'overlayPane', + + // @option attribution: String = null + // String to be shown in the attribution control, e.g. "© OpenStreetMap contributors". It describes the layer data and is often a legal obligation towards copyright holders and tile providers. + attribution: null, + + bubblingMouseEvents: true + }, + + /* @section + * Classes extending `L.Layer` will inherit the following methods: + * + * @method addTo(map: Map|LayerGroup): this + * Adds the layer to the given map or layer group. + */ + addTo: function (map) { + map.addLayer(this); + return this; + }, + + // @method remove: this + // Removes the layer from the map it is currently active on. + remove: function () { + return this.removeFrom(this._map || this._mapToAdd); + }, + + // @method removeFrom(map: Map): this + // Removes the layer from the given map + // + // @alternative + // @method removeFrom(group: LayerGroup): this + // Removes the layer from the given `LayerGroup` + removeFrom: function (obj) { + if (obj) { + obj.removeLayer(this); + } + return this; + }, + + // @method getPane(name? : String): HTMLElement + // Returns the `HTMLElement` representing the named pane on the map. If `name` is omitted, returns the pane for this layer. + getPane: function (name) { + return this._map.getPane(name ? (this.options[name] || name) : this.options.pane); + }, + + addInteractiveTarget: function (targetEl) { + this._map._targets[stamp(targetEl)] = this; + return this; + }, + + removeInteractiveTarget: function (targetEl) { + delete this._map._targets[stamp(targetEl)]; + return this; + }, + + // @method getAttribution: String + // Used by the `attribution control`, returns the [attribution option](#gridlayer-attribution). + getAttribution: function () { + return this.options.attribution; + }, + + _layerAdd: function (e) { + var map = e.target; + + // check in case layer gets added and then removed before the map is ready + if (!map.hasLayer(this)) { return; } + + this._map = map; + this._zoomAnimated = map._zoomAnimated; + + if (this.getEvents) { + var events = this.getEvents(); + map.on(events, this); + this.once('remove', function () { + map.off(events, this); + }, this); + } + + this.onAdd(map); + + this.fire('add'); + map.fire('layeradd', {layer: this}); + } +}); + +/* @section Extension methods + * @uninheritable + * + * Every layer should extend from `L.Layer` and (re-)implement the following methods. + * + * @method onAdd(map: Map): this + * Should contain code that creates DOM elements for the layer, adds them to `map panes` where they should belong and puts listeners on relevant map events. Called on [`map.addLayer(layer)`](#map-addlayer). + * + * @method onRemove(map: Map): this + * Should contain all clean up code that removes the layer's elements from the DOM and removes listeners previously added in [`onAdd`](#layer-onadd). Called on [`map.removeLayer(layer)`](#map-removelayer). + * + * @method getEvents(): Object + * This optional method should return an object like `{ viewreset: this._reset }` for [`addEventListener`](#evented-addeventlistener). The event handlers in this object will be automatically added and removed from the map with your layer. + * + * @method getAttribution(): String + * This optional method should return a string containing HTML to be shown on the `Attribution control` whenever the layer is visible. + * + * @method beforeAdd(map: Map): this + * Optional method. Called on [`map.addLayer(layer)`](#map-addlayer), before the layer is added to the map, before events are initialized, without waiting until the map is in a usable state. Use for early initialization only. + */ + + +/* @namespace Map + * @section Layer events + * + * @event layeradd: LayerEvent + * Fired when a new layer is added to the map. + * + * @event layerremove: LayerEvent + * Fired when some layer is removed from the map + * + * @section Methods for Layers and Controls + */ +Map.include({ + // @method addLayer(layer: Layer): this + // Adds the given layer to the map + addLayer: function (layer) { + if (!layer._layerAdd) { + throw new Error('The provided object is not a Layer.'); + } + + var id = stamp(layer); + if (this._layers[id]) { return this; } + this._layers[id] = layer; + + layer._mapToAdd = this; + + if (layer.beforeAdd) { + layer.beforeAdd(this); + } + + this.whenReady(layer._layerAdd, layer); + + return this; + }, + + // @method removeLayer(layer: Layer): this + // Removes the given layer from the map. + removeLayer: function (layer) { + var id = stamp(layer); + + if (!this._layers[id]) { return this; } + + if (this._loaded) { + layer.onRemove(this); + } + + delete this._layers[id]; + + if (this._loaded) { + this.fire('layerremove', {layer: layer}); + layer.fire('remove'); + } + + layer._map = layer._mapToAdd = null; + + return this; + }, + + // @method hasLayer(layer: Layer): Boolean + // Returns `true` if the given layer is currently added to the map + hasLayer: function (layer) { + return stamp(layer) in this._layers; + }, + + /* @method eachLayer(fn: Function, context?: Object): this + * Iterates over the layers of the map, optionally specifying context of the iterator function. + * ``` + * map.eachLayer(function(layer){ + * layer.bindPopup('Hello'); + * }); + * ``` + */ + eachLayer: function (method, context) { + for (var i in this._layers) { + method.call(context, this._layers[i]); + } + return this; + }, + + _addLayers: function (layers) { + layers = layers ? (isArray(layers) ? layers : [layers]) : []; + + for (var i = 0, len = layers.length; i < len; i++) { + this.addLayer(layers[i]); + } + }, + + _addZoomLimit: function (layer) { + if (!isNaN(layer.options.maxZoom) || !isNaN(layer.options.minZoom)) { + this._zoomBoundLayers[stamp(layer)] = layer; + this._updateZoomLevels(); + } + }, + + _removeZoomLimit: function (layer) { + var id = stamp(layer); + + if (this._zoomBoundLayers[id]) { + delete this._zoomBoundLayers[id]; + this._updateZoomLevels(); + } + }, + + _updateZoomLevels: function () { + var minZoom = Infinity, + maxZoom = -Infinity, + oldZoomSpan = this._getZoomSpan(); + + for (var i in this._zoomBoundLayers) { + var options = this._zoomBoundLayers[i].options; + + minZoom = options.minZoom === undefined ? minZoom : Math.min(minZoom, options.minZoom); + maxZoom = options.maxZoom === undefined ? maxZoom : Math.max(maxZoom, options.maxZoom); + } + + this._layersMaxZoom = maxZoom === -Infinity ? undefined : maxZoom; + this._layersMinZoom = minZoom === Infinity ? undefined : minZoom; + + // @section Map state change events + // @event zoomlevelschange: Event + // Fired when the number of zoomlevels on the map is changed due + // to adding or removing a layer. + if (oldZoomSpan !== this._getZoomSpan()) { + this.fire('zoomlevelschange'); + } + + if (this.options.maxZoom === undefined && this._layersMaxZoom && this.getZoom() > this._layersMaxZoom) { + this.setZoom(this._layersMaxZoom); + } + if (this.options.minZoom === undefined && this._layersMinZoom && this.getZoom() < this._layersMinZoom) { + this.setZoom(this._layersMinZoom); + } + } +}); + +/* + * @class LayerGroup + * @aka L.LayerGroup + * @inherits Interactive layer + * + * Used to group several layers and handle them as one. If you add it to the map, + * any layers added or removed from the group will be added/removed on the map as + * well. Extends `Layer`. + * + * @example + * + * ```js + * L.layerGroup([marker1, marker2]) + * .addLayer(polyline) + * .addTo(map); + * ``` + */ + +var LayerGroup = Layer.extend({ + + initialize: function (layers, options) { + setOptions(this, options); + + this._layers = {}; + + var i, len; + + if (layers) { + for (i = 0, len = layers.length; i < len; i++) { + this.addLayer(layers[i]); + } + } + }, + + // @method addLayer(layer: Layer): this + // Adds the given layer to the group. + addLayer: function (layer) { + var id = this.getLayerId(layer); + + this._layers[id] = layer; + + if (this._map) { + this._map.addLayer(layer); + } + + return this; + }, + + // @method removeLayer(layer: Layer): this + // Removes the given layer from the group. + // @alternative + // @method removeLayer(id: Number): this + // Removes the layer with the given internal ID from the group. + removeLayer: function (layer) { + var id = layer in this._layers ? layer : this.getLayerId(layer); + + if (this._map && this._layers[id]) { + this._map.removeLayer(this._layers[id]); + } + + delete this._layers[id]; + + return this; + }, + + // @method hasLayer(layer: Layer): Boolean + // Returns `true` if the given layer is currently added to the group. + // @alternative + // @method hasLayer(id: Number): Boolean + // Returns `true` if the given internal ID is currently added to the group. + hasLayer: function (layer) { + var layerId = typeof layer === 'number' ? layer : this.getLayerId(layer); + return layerId in this._layers; + }, + + // @method clearLayers(): this + // Removes all the layers from the group. + clearLayers: function () { + return this.eachLayer(this.removeLayer, this); + }, + + // @method invoke(methodName: String, …): this + // Calls `methodName` on every layer contained in this group, passing any + // additional parameters. Has no effect if the layers contained do not + // implement `methodName`. + invoke: function (methodName) { + var args = Array.prototype.slice.call(arguments, 1), + i, layer; + + for (i in this._layers) { + layer = this._layers[i]; + + if (layer[methodName]) { + layer[methodName].apply(layer, args); + } + } + + return this; + }, + + onAdd: function (map) { + this.eachLayer(map.addLayer, map); + }, + + onRemove: function (map) { + this.eachLayer(map.removeLayer, map); + }, + + // @method eachLayer(fn: Function, context?: Object): this + // Iterates over the layers of the group, optionally specifying context of the iterator function. + // ```js + // group.eachLayer(function (layer) { + // layer.bindPopup('Hello'); + // }); + // ``` + eachLayer: function (method, context) { + for (var i in this._layers) { + method.call(context, this._layers[i]); + } + return this; + }, + + // @method getLayer(id: Number): Layer + // Returns the layer with the given internal ID. + getLayer: function (id) { + return this._layers[id]; + }, + + // @method getLayers(): Layer[] + // Returns an array of all the layers added to the group. + getLayers: function () { + var layers = []; + this.eachLayer(layers.push, layers); + return layers; + }, + + // @method setZIndex(zIndex: Number): this + // Calls `setZIndex` on every layer contained in this group, passing the z-index. + setZIndex: function (zIndex) { + return this.invoke('setZIndex', zIndex); + }, + + // @method getLayerId(layer: Layer): Number + // Returns the internal ID for a layer + getLayerId: function (layer) { + return stamp(layer); + } +}); + + +// @factory L.layerGroup(layers?: Layer[], options?: Object) +// Create a layer group, optionally given an initial set of layers and an `options` object. +var layerGroup = function (layers, options) { + return new LayerGroup(layers, options); +}; + +/* + * @class FeatureGroup + * @aka L.FeatureGroup + * @inherits LayerGroup + * + * Extended `LayerGroup` that makes it easier to do the same thing to all its member layers: + * * [`bindPopup`](#layer-bindpopup) binds a popup to all of the layers at once (likewise with [`bindTooltip`](#layer-bindtooltip)) + * * Events are propagated to the `FeatureGroup`, so if the group has an event + * handler, it will handle events from any of the layers. This includes mouse events + * and custom events. + * * Has `layeradd` and `layerremove` events + * + * @example + * + * ```js + * L.featureGroup([marker1, marker2, polyline]) + * .bindPopup('Hello world!') + * .on('click', function() { alert('Clicked on a member of the group!'); }) + * .addTo(map); + * ``` + */ + +var FeatureGroup = LayerGroup.extend({ + + addLayer: function (layer) { + if (this.hasLayer(layer)) { + return this; + } + + layer.addEventParent(this); + + LayerGroup.prototype.addLayer.call(this, layer); + + // @event layeradd: LayerEvent + // Fired when a layer is added to this `FeatureGroup` + return this.fire('layeradd', {layer: layer}); + }, + + removeLayer: function (layer) { + if (!this.hasLayer(layer)) { + return this; + } + if (layer in this._layers) { + layer = this._layers[layer]; + } + + layer.removeEventParent(this); + + LayerGroup.prototype.removeLayer.call(this, layer); + + // @event layerremove: LayerEvent + // Fired when a layer is removed from this `FeatureGroup` + return this.fire('layerremove', {layer: layer}); + }, + + // @method setStyle(style: Path options): this + // Sets the given path options to each layer of the group that has a `setStyle` method. + setStyle: function (style) { + return this.invoke('setStyle', style); + }, + + // @method bringToFront(): this + // Brings the layer group to the top of all other layers + bringToFront: function () { + return this.invoke('bringToFront'); + }, + + // @method bringToBack(): this + // Brings the layer group to the back of all other layers + bringToBack: function () { + return this.invoke('bringToBack'); + }, + + // @method getBounds(): LatLngBounds + // Returns the LatLngBounds of the Feature Group (created from bounds and coordinates of its children). + getBounds: function () { + var bounds = new LatLngBounds(); + + for (var id in this._layers) { + var layer = this._layers[id]; + bounds.extend(layer.getBounds ? layer.getBounds() : layer.getLatLng()); + } + return bounds; + } +}); + +// @factory L.featureGroup(layers?: Layer[], options?: Object) +// Create a feature group, optionally given an initial set of layers and an `options` object. +var featureGroup = function (layers, options) { + return new FeatureGroup(layers, options); +}; + +/* + * @class Icon + * @aka L.Icon + * + * Represents an icon to provide when creating a marker. + * + * @example + * + * ```js + * var myIcon = L.icon({ + * iconUrl: 'my-icon.png', + * iconRetinaUrl: 'my-icon@2x.png', + * iconSize: [38, 95], + * iconAnchor: [22, 94], + * popupAnchor: [-3, -76], + * shadowUrl: 'my-icon-shadow.png', + * shadowRetinaUrl: 'my-icon-shadow@2x.png', + * shadowSize: [68, 95], + * shadowAnchor: [22, 94] + * }); + * + * L.marker([50.505, 30.57], {icon: myIcon}).addTo(map); + * ``` + * + * `L.Icon.Default` extends `L.Icon` and is the blue icon Leaflet uses for markers by default. + * + */ + +var Icon = Class.extend({ + + /* @section + * @aka Icon options + * + * @option iconUrl: String = null + * **(required)** The URL to the icon image (absolute or relative to your script path). + * + * @option iconRetinaUrl: String = null + * The URL to a retina sized version of the icon image (absolute or relative to your + * script path). Used for Retina screen devices. + * + * @option iconSize: Point = null + * Size of the icon image in pixels. + * + * @option iconAnchor: Point = null + * The coordinates of the "tip" of the icon (relative to its top left corner). The icon + * will be aligned so that this point is at the marker's geographical location. Centered + * by default if size is specified, also can be set in CSS with negative margins. + * + * @option popupAnchor: Point = [0, 0] + * The coordinates of the point from which popups will "open", relative to the icon anchor. + * + * @option tooltipAnchor: Point = [0, 0] + * The coordinates of the point from which tooltips will "open", relative to the icon anchor. + * + * @option shadowUrl: String = null + * The URL to the icon shadow image. If not specified, no shadow image will be created. + * + * @option shadowRetinaUrl: String = null + * + * @option shadowSize: Point = null + * Size of the shadow image in pixels. + * + * @option shadowAnchor: Point = null + * The coordinates of the "tip" of the shadow (relative to its top left corner) (the same + * as iconAnchor if not specified). + * + * @option className: String = '' + * A custom class name to assign to both icon and shadow images. Empty by default. + */ + + options: { + popupAnchor: [0, 0], + tooltipAnchor: [0, 0], + + // @option crossOrigin: Boolean|String = false + // Whether the crossOrigin attribute will be added to the tiles. + // If a String is provided, all tiles will have their crossOrigin attribute set to the String provided. This is needed if you want to access tile pixel data. + // Refer to [CORS Settings](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes) for valid String values. + crossOrigin: false + }, + + initialize: function (options) { + setOptions(this, options); + }, + + // @method createIcon(oldIcon?: HTMLElement): HTMLElement + // Called internally when the icon has to be shown, returns a `` HTML element + // styled according to the options. + createIcon: function (oldIcon) { + return this._createIcon('icon', oldIcon); + }, + + // @method createShadow(oldIcon?: HTMLElement): HTMLElement + // As `createIcon`, but for the shadow beneath it. + createShadow: function (oldIcon) { + return this._createIcon('shadow', oldIcon); + }, + + _createIcon: function (name, oldIcon) { + var src = this._getIconUrl(name); + + if (!src) { + if (name === 'icon') { + throw new Error('iconUrl not set in Icon options (see the docs).'); + } + return null; + } + + var img = this._createImg(src, oldIcon && oldIcon.tagName === 'IMG' ? oldIcon : null); + this._setIconStyles(img, name); + + if (this.options.crossOrigin || this.options.crossOrigin === '') { + img.crossOrigin = this.options.crossOrigin === true ? '' : this.options.crossOrigin; + } + + return img; + }, + + _setIconStyles: function (img, name) { + var options = this.options; + var sizeOption = options[name + 'Size']; + + if (typeof sizeOption === 'number') { + sizeOption = [sizeOption, sizeOption]; + } + + var size = toPoint(sizeOption), + anchor = toPoint(name === 'shadow' && options.shadowAnchor || options.iconAnchor || + size && size.divideBy(2, true)); + + img.className = 'leaflet-marker-' + name + ' ' + (options.className || ''); + + if (anchor) { + img.style.marginLeft = (-anchor.x) + 'px'; + img.style.marginTop = (-anchor.y) + 'px'; + } + + if (size) { + img.style.width = size.x + 'px'; + img.style.height = size.y + 'px'; + } + }, + + _createImg: function (src, el) { + el = el || document.createElement('img'); + el.src = src; + return el; + }, + + _getIconUrl: function (name) { + return Browser.retina && this.options[name + 'RetinaUrl'] || this.options[name + 'Url']; + } +}); + + +// @factory L.icon(options: Icon options) +// Creates an icon instance with the given options. +function icon(options) { + return new Icon(options); +} + +/* + * @miniclass Icon.Default (Icon) + * @aka L.Icon.Default + * @section + * + * A trivial subclass of `Icon`, represents the icon to use in `Marker`s when + * no icon is specified. Points to the blue marker image distributed with Leaflet + * releases. + * + * In order to customize the default icon, just change the properties of `L.Icon.Default.prototype.options` + * (which is a set of `Icon options`). + * + * If you want to _completely_ replace the default icon, override the + * `L.Marker.prototype.options.icon` with your own icon instead. + */ + +var IconDefault = Icon.extend({ + + options: { + iconUrl: 'marker-icon.png', + iconRetinaUrl: 'marker-icon-2x.png', + shadowUrl: 'marker-shadow.png', + iconSize: [25, 41], + iconAnchor: [12, 41], + popupAnchor: [1, -34], + tooltipAnchor: [16, -28], + shadowSize: [41, 41] + }, + + _getIconUrl: function (name) { + if (typeof IconDefault.imagePath !== 'string') { // Deprecated, backwards-compatibility only + IconDefault.imagePath = this._detectIconPath(); + } + + // @option imagePath: String + // `Icon.Default` will try to auto-detect the location of the + // blue icon images. If you are placing these images in a non-standard + // way, set this option to point to the right path. + return (this.options.imagePath || IconDefault.imagePath) + Icon.prototype._getIconUrl.call(this, name); + }, + + _stripUrl: function (path) { // separate function to use in tests + var strip = function (str, re, idx) { + var match = re.exec(str); + return match && match[idx]; + }; + path = strip(path, /^url\((['"])?(.+)\1\)$/, 2); + return path && strip(path, /^(.*)marker-icon\.png$/, 1); + }, + + _detectIconPath: function () { + var el = create$1('div', 'leaflet-default-icon-path', document.body); + var path = getStyle(el, 'background-image') || + getStyle(el, 'backgroundImage'); // IE8 + + document.body.removeChild(el); + path = this._stripUrl(path); + if (path) { return path; } + var link = document.querySelector('link[href$="leaflet.css"]'); + if (!link) { return ''; } + return link.href.substring(0, link.href.length - 'leaflet.css'.length - 1); + } +}); + +/* + * L.Handler.MarkerDrag is used internally by L.Marker to make the markers draggable. + */ + + +/* @namespace Marker + * @section Interaction handlers + * + * Interaction handlers are properties of a marker instance that allow you to control interaction behavior in runtime, enabling or disabling certain features such as dragging (see `Handler` methods). Example: + * + * ```js + * marker.dragging.disable(); + * ``` + * + * @property dragging: Handler + * Marker dragging handler (by both mouse and touch). Only valid when the marker is on the map (Otherwise set [`marker.options.draggable`](#marker-draggable)). + */ + +var MarkerDrag = Handler.extend({ + initialize: function (marker) { + this._marker = marker; + }, + + addHooks: function () { + var icon = this._marker._icon; + + if (!this._draggable) { + this._draggable = new Draggable(icon, icon, true); + } + + this._draggable.on({ + dragstart: this._onDragStart, + predrag: this._onPreDrag, + drag: this._onDrag, + dragend: this._onDragEnd + }, this).enable(); + + addClass(icon, 'leaflet-marker-draggable'); + }, + + removeHooks: function () { + this._draggable.off({ + dragstart: this._onDragStart, + predrag: this._onPreDrag, + drag: this._onDrag, + dragend: this._onDragEnd + }, this).disable(); + + if (this._marker._icon) { + removeClass(this._marker._icon, 'leaflet-marker-draggable'); + } + }, + + moved: function () { + return this._draggable && this._draggable._moved; + }, + + _adjustPan: function (e) { + var marker = this._marker, + map = marker._map, + speed = this._marker.options.autoPanSpeed, + padding = this._marker.options.autoPanPadding, + iconPos = getPosition(marker._icon), + bounds = map.getPixelBounds(), + origin = map.getPixelOrigin(); + + var panBounds = toBounds( + bounds.min._subtract(origin).add(padding), + bounds.max._subtract(origin).subtract(padding) + ); + + if (!panBounds.contains(iconPos)) { + // Compute incremental movement + var movement = toPoint( + (Math.max(panBounds.max.x, iconPos.x) - panBounds.max.x) / (bounds.max.x - panBounds.max.x) - + (Math.min(panBounds.min.x, iconPos.x) - panBounds.min.x) / (bounds.min.x - panBounds.min.x), + + (Math.max(panBounds.max.y, iconPos.y) - panBounds.max.y) / (bounds.max.y - panBounds.max.y) - + (Math.min(panBounds.min.y, iconPos.y) - panBounds.min.y) / (bounds.min.y - panBounds.min.y) + ).multiplyBy(speed); + + map.panBy(movement, {animate: false}); + + this._draggable._newPos._add(movement); + this._draggable._startPos._add(movement); + + setPosition(marker._icon, this._draggable._newPos); + this._onDrag(e); + + this._panRequest = requestAnimFrame(this._adjustPan.bind(this, e)); + } + }, + + _onDragStart: function () { + // @section Dragging events + // @event dragstart: Event + // Fired when the user starts dragging the marker. + + // @event movestart: Event + // Fired when the marker starts moving (because of dragging). + + this._oldLatLng = this._marker.getLatLng(); + + // When using ES6 imports it could not be set when `Popup` was not imported as well + this._marker.closePopup && this._marker.closePopup(); + + this._marker + .fire('movestart') + .fire('dragstart'); + }, + + _onPreDrag: function (e) { + if (this._marker.options.autoPan) { + cancelAnimFrame(this._panRequest); + this._panRequest = requestAnimFrame(this._adjustPan.bind(this, e)); + } + }, + + _onDrag: function (e) { + var marker = this._marker, + shadow = marker._shadow, + iconPos = getPosition(marker._icon), + latlng = marker._map.layerPointToLatLng(iconPos); + + // update shadow position + if (shadow) { + setPosition(shadow, iconPos); + } + + marker._latlng = latlng; + e.latlng = latlng; + e.oldLatLng = this._oldLatLng; + + // @event drag: Event + // Fired repeatedly while the user drags the marker. + marker + .fire('move', e) + .fire('drag', e); + }, + + _onDragEnd: function (e) { + // @event dragend: DragEndEvent + // Fired when the user stops dragging the marker. + + cancelAnimFrame(this._panRequest); + + // @event moveend: Event + // Fired when the marker stops moving (because of dragging). + delete this._oldLatLng; + this._marker + .fire('moveend') + .fire('dragend', e); + } +}); + +/* + * @class Marker + * @inherits Interactive layer + * @aka L.Marker + * L.Marker is used to display clickable/draggable icons on the map. Extends `Layer`. + * + * @example + * + * ```js + * L.marker([50.5, 30.5]).addTo(map); + * ``` + */ + +var Marker = Layer.extend({ + + // @section + // @aka Marker options + options: { + // @option icon: Icon = * + // Icon instance to use for rendering the marker. + // See [Icon documentation](#L.Icon) for details on how to customize the marker icon. + // If not specified, a common instance of `L.Icon.Default` is used. + icon: new IconDefault(), + + // Option inherited from "Interactive layer" abstract class + interactive: true, + + // @option keyboard: Boolean = true + // Whether the marker can be tabbed to with a keyboard and clicked by pressing enter. + keyboard: true, + + // @option title: String = '' + // Text for the browser tooltip that appear on marker hover (no tooltip by default). + // [Useful for accessibility](https://leafletjs.com/examples/accessibility/#markers-must-be-labelled). + title: '', + + // @option alt: String = 'Marker' + // Text for the `alt` attribute of the icon image. + // [Useful for accessibility](https://leafletjs.com/examples/accessibility/#markers-must-be-labelled). + alt: 'Marker', + + // @option zIndexOffset: Number = 0 + // By default, marker images zIndex is set automatically based on its latitude. Use this option if you want to put the marker on top of all others (or below), specifying a high value like `1000` (or high negative value, respectively). + zIndexOffset: 0, + + // @option opacity: Number = 1.0 + // The opacity of the marker. + opacity: 1, + + // @option riseOnHover: Boolean = false + // If `true`, the marker will get on top of others when you hover the mouse over it. + riseOnHover: false, + + // @option riseOffset: Number = 250 + // The z-index offset used for the `riseOnHover` feature. + riseOffset: 250, + + // @option pane: String = 'markerPane' + // `Map pane` where the markers icon will be added. + pane: 'markerPane', + + // @option shadowPane: String = 'shadowPane' + // `Map pane` where the markers shadow will be added. + shadowPane: 'shadowPane', + + // @option bubblingMouseEvents: Boolean = false + // When `true`, a mouse event on this marker will trigger the same event on the map + // (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used). + bubblingMouseEvents: false, + + // @option autoPanOnFocus: Boolean = true + // When `true`, the map will pan whenever the marker is focused (via + // e.g. pressing `tab` on the keyboard) to ensure the marker is + // visible within the map's bounds + autoPanOnFocus: true, + + // @section Draggable marker options + // @option draggable: Boolean = false + // Whether the marker is draggable with mouse/touch or not. + draggable: false, + + // @option autoPan: Boolean = false + // Whether to pan the map when dragging this marker near its edge or not. + autoPan: false, + + // @option autoPanPadding: Point = Point(50, 50) + // Distance (in pixels to the left/right and to the top/bottom) of the + // map edge to start panning the map. + autoPanPadding: [50, 50], + + // @option autoPanSpeed: Number = 10 + // Number of pixels the map should pan by. + autoPanSpeed: 10 + }, + + /* @section + * + * In addition to [shared layer methods](#Layer) like `addTo()` and `remove()` and [popup methods](#Popup) like bindPopup() you can also use the following methods: + */ + + initialize: function (latlng, options) { + setOptions(this, options); + this._latlng = toLatLng(latlng); + }, + + onAdd: function (map) { + this._zoomAnimated = this._zoomAnimated && map.options.markerZoomAnimation; + + if (this._zoomAnimated) { + map.on('zoomanim', this._animateZoom, this); + } + + this._initIcon(); + this.update(); + }, + + onRemove: function (map) { + if (this.dragging && this.dragging.enabled()) { + this.options.draggable = true; + this.dragging.removeHooks(); + } + delete this.dragging; + + if (this._zoomAnimated) { + map.off('zoomanim', this._animateZoom, this); + } + + this._removeIcon(); + this._removeShadow(); + }, + + getEvents: function () { + return { + zoom: this.update, + viewreset: this.update + }; + }, + + // @method getLatLng: LatLng + // Returns the current geographical position of the marker. + getLatLng: function () { + return this._latlng; + }, + + // @method setLatLng(latlng: LatLng): this + // Changes the marker position to the given point. + setLatLng: function (latlng) { + var oldLatLng = this._latlng; + this._latlng = toLatLng(latlng); + this.update(); + + // @event move: Event + // Fired when the marker is moved via [`setLatLng`](#marker-setlatlng) or by [dragging](#marker-dragging). Old and new coordinates are included in event arguments as `oldLatLng`, `latlng`. + return this.fire('move', {oldLatLng: oldLatLng, latlng: this._latlng}); + }, + + // @method setZIndexOffset(offset: Number): this + // Changes the [zIndex offset](#marker-zindexoffset) of the marker. + setZIndexOffset: function (offset) { + this.options.zIndexOffset = offset; + return this.update(); + }, + + // @method getIcon: Icon + // Returns the current icon used by the marker + getIcon: function () { + return this.options.icon; + }, + + // @method setIcon(icon: Icon): this + // Changes the marker icon. + setIcon: function (icon) { + + this.options.icon = icon; + + if (this._map) { + this._initIcon(); + this.update(); + } + + if (this._popup) { + this.bindPopup(this._popup, this._popup.options); + } + + return this; + }, + + getElement: function () { + return this._icon; + }, + + update: function () { + + if (this._icon && this._map) { + var pos = this._map.latLngToLayerPoint(this._latlng).round(); + this._setPos(pos); + } + + return this; + }, + + _initIcon: function () { + var options = this.options, + classToAdd = 'leaflet-zoom-' + (this._zoomAnimated ? 'animated' : 'hide'); + + var icon = options.icon.createIcon(this._icon), + addIcon = false; + + // if we're not reusing the icon, remove the old one and init new one + if (icon !== this._icon) { + if (this._icon) { + this._removeIcon(); + } + addIcon = true; + + if (options.title) { + icon.title = options.title; + } + + if (icon.tagName === 'IMG') { + icon.alt = options.alt || ''; + } + } + + addClass(icon, classToAdd); + + if (options.keyboard) { + icon.tabIndex = '0'; + icon.setAttribute('role', 'button'); + } + + this._icon = icon; + + if (options.riseOnHover) { + this.on({ + mouseover: this._bringToFront, + mouseout: this._resetZIndex + }); + } + + if (this.options.autoPanOnFocus) { + on(icon, 'focus', this._panOnFocus, this); + } + + var newShadow = options.icon.createShadow(this._shadow), + addShadow = false; + + if (newShadow !== this._shadow) { + this._removeShadow(); + addShadow = true; + } + + if (newShadow) { + addClass(newShadow, classToAdd); + newShadow.alt = ''; + } + this._shadow = newShadow; + + + if (options.opacity < 1) { + this._updateOpacity(); + } + + + if (addIcon) { + this.getPane().appendChild(this._icon); + } + this._initInteraction(); + if (newShadow && addShadow) { + this.getPane(options.shadowPane).appendChild(this._shadow); + } + }, + + _removeIcon: function () { + if (this.options.riseOnHover) { + this.off({ + mouseover: this._bringToFront, + mouseout: this._resetZIndex + }); + } + + if (this.options.autoPanOnFocus) { + off(this._icon, 'focus', this._panOnFocus, this); + } + + remove(this._icon); + this.removeInteractiveTarget(this._icon); + + this._icon = null; + }, + + _removeShadow: function () { + if (this._shadow) { + remove(this._shadow); + } + this._shadow = null; + }, + + _setPos: function (pos) { + + if (this._icon) { + setPosition(this._icon, pos); + } + + if (this._shadow) { + setPosition(this._shadow, pos); + } + + this._zIndex = pos.y + this.options.zIndexOffset; + + this._resetZIndex(); + }, + + _updateZIndex: function (offset) { + if (this._icon) { + this._icon.style.zIndex = this._zIndex + offset; + } + }, + + _animateZoom: function (opt) { + var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center).round(); + + this._setPos(pos); + }, + + _initInteraction: function () { + + if (!this.options.interactive) { return; } + + addClass(this._icon, 'leaflet-interactive'); + + this.addInteractiveTarget(this._icon); + + if (MarkerDrag) { + var draggable = this.options.draggable; + if (this.dragging) { + draggable = this.dragging.enabled(); + this.dragging.disable(); + } + + this.dragging = new MarkerDrag(this); + + if (draggable) { + this.dragging.enable(); + } + } + }, + + // @method setOpacity(opacity: Number): this + // Changes the opacity of the marker. + setOpacity: function (opacity) { + this.options.opacity = opacity; + if (this._map) { + this._updateOpacity(); + } + + return this; + }, + + _updateOpacity: function () { + var opacity = this.options.opacity; + + if (this._icon) { + setOpacity(this._icon, opacity); + } + + if (this._shadow) { + setOpacity(this._shadow, opacity); + } + }, + + _bringToFront: function () { + this._updateZIndex(this.options.riseOffset); + }, + + _resetZIndex: function () { + this._updateZIndex(0); + }, + + _panOnFocus: function () { + var map = this._map; + if (!map) { return; } + + var iconOpts = this.options.icon.options; + var size = iconOpts.iconSize ? toPoint(iconOpts.iconSize) : toPoint(0, 0); + var anchor = iconOpts.iconAnchor ? toPoint(iconOpts.iconAnchor) : toPoint(0, 0); + + map.panInside(this._latlng, { + paddingTopLeft: anchor, + paddingBottomRight: size.subtract(anchor) + }); + }, + + _getPopupAnchor: function () { + return this.options.icon.options.popupAnchor; + }, + + _getTooltipAnchor: function () { + return this.options.icon.options.tooltipAnchor; + } +}); + + +// factory L.marker(latlng: LatLng, options? : Marker options) + +// @factory L.marker(latlng: LatLng, options? : Marker options) +// Instantiates a Marker object given a geographical point and optionally an options object. +function marker(latlng, options) { + return new Marker(latlng, options); +} + +/* + * @class Path + * @aka L.Path + * @inherits Interactive layer + * + * An abstract class that contains options and constants shared between vector + * overlays (Polygon, Polyline, Circle). Do not use it directly. Extends `Layer`. + */ + +var Path = Layer.extend({ + + // @section + // @aka Path options + options: { + // @option stroke: Boolean = true + // Whether to draw stroke along the path. Set it to `false` to disable borders on polygons or circles. + stroke: true, + + // @option color: String = '#3388ff' + // Stroke color + color: '#3388ff', + + // @option weight: Number = 3 + // Stroke width in pixels + weight: 3, + + // @option opacity: Number = 1.0 + // Stroke opacity + opacity: 1, + + // @option lineCap: String= 'round' + // A string that defines [shape to be used at the end](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linecap) of the stroke. + lineCap: 'round', + + // @option lineJoin: String = 'round' + // A string that defines [shape to be used at the corners](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linejoin) of the stroke. + lineJoin: 'round', + + // @option dashArray: String = null + // A string that defines the stroke [dash pattern](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-dasharray). Doesn't work on `Canvas`-powered layers in [some old browsers](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/setLineDash#Browser_compatibility). + dashArray: null, + + // @option dashOffset: String = null + // A string that defines the [distance into the dash pattern to start the dash](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-dashoffset). Doesn't work on `Canvas`-powered layers in [some old browsers](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/setLineDash#Browser_compatibility). + dashOffset: null, + + // @option fill: Boolean = depends + // Whether to fill the path with color. Set it to `false` to disable filling on polygons or circles. + fill: false, + + // @option fillColor: String = * + // Fill color. Defaults to the value of the [`color`](#path-color) option + fillColor: null, + + // @option fillOpacity: Number = 0.2 + // Fill opacity. + fillOpacity: 0.2, + + // @option fillRule: String = 'evenodd' + // A string that defines [how the inside of a shape](https://developer.mozilla.org/docs/Web/SVG/Attribute/fill-rule) is determined. + fillRule: 'evenodd', + + // className: '', + + // Option inherited from "Interactive layer" abstract class + interactive: true, + + // @option bubblingMouseEvents: Boolean = true + // When `true`, a mouse event on this path will trigger the same event on the map + // (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used). + bubblingMouseEvents: true + }, + + beforeAdd: function (map) { + // Renderer is set here because we need to call renderer.getEvents + // before this.getEvents. + this._renderer = map.getRenderer(this); + }, + + onAdd: function () { + this._renderer._initPath(this); + this._reset(); + this._renderer._addPath(this); + }, + + onRemove: function () { + this._renderer._removePath(this); + }, + + // @method redraw(): this + // Redraws the layer. Sometimes useful after you changed the coordinates that the path uses. + redraw: function () { + if (this._map) { + this._renderer._updatePath(this); + } + return this; + }, + + // @method setStyle(style: Path options): this + // Changes the appearance of a Path based on the options in the `Path options` object. + setStyle: function (style) { + setOptions(this, style); + if (this._renderer) { + this._renderer._updateStyle(this); + if (this.options.stroke && style && Object.prototype.hasOwnProperty.call(style, 'weight')) { + this._updateBounds(); + } + } + return this; + }, + + // @method bringToFront(): this + // Brings the layer to the top of all path layers. + bringToFront: function () { + if (this._renderer) { + this._renderer._bringToFront(this); + } + return this; + }, + + // @method bringToBack(): this + // Brings the layer to the bottom of all path layers. + bringToBack: function () { + if (this._renderer) { + this._renderer._bringToBack(this); + } + return this; + }, + + getElement: function () { + return this._path; + }, + + _reset: function () { + // defined in child classes + this._project(); + this._update(); + }, + + _clickTolerance: function () { + // used when doing hit detection for Canvas layers + return (this.options.stroke ? this.options.weight / 2 : 0) + + (this._renderer.options.tolerance || 0); + } +}); + +/* + * @class CircleMarker + * @aka L.CircleMarker + * @inherits Path + * + * A circle of a fixed size with radius specified in pixels. Extends `Path`. + */ + +var CircleMarker = Path.extend({ + + // @section + // @aka CircleMarker options + options: { + fill: true, + + // @option radius: Number = 10 + // Radius of the circle marker, in pixels + radius: 10 + }, + + initialize: function (latlng, options) { + setOptions(this, options); + this._latlng = toLatLng(latlng); + this._radius = this.options.radius; + }, + + // @method setLatLng(latLng: LatLng): this + // Sets the position of a circle marker to a new location. + setLatLng: function (latlng) { + var oldLatLng = this._latlng; + this._latlng = toLatLng(latlng); + this.redraw(); + + // @event move: Event + // Fired when the marker is moved via [`setLatLng`](#circlemarker-setlatlng). Old and new coordinates are included in event arguments as `oldLatLng`, `latlng`. + return this.fire('move', {oldLatLng: oldLatLng, latlng: this._latlng}); + }, + + // @method getLatLng(): LatLng + // Returns the current geographical position of the circle marker + getLatLng: function () { + return this._latlng; + }, + + // @method setRadius(radius: Number): this + // Sets the radius of a circle marker. Units are in pixels. + setRadius: function (radius) { + this.options.radius = this._radius = radius; + return this.redraw(); + }, + + // @method getRadius(): Number + // Returns the current radius of the circle + getRadius: function () { + return this._radius; + }, + + setStyle : function (options) { + var radius = options && options.radius || this._radius; + Path.prototype.setStyle.call(this, options); + this.setRadius(radius); + return this; + }, + + _project: function () { + this._point = this._map.latLngToLayerPoint(this._latlng); + this._updateBounds(); + }, + + _updateBounds: function () { + var r = this._radius, + r2 = this._radiusY || r, + w = this._clickTolerance(), + p = [r + w, r2 + w]; + this._pxBounds = new Bounds(this._point.subtract(p), this._point.add(p)); + }, + + _update: function () { + if (this._map) { + this._updatePath(); + } + }, + + _updatePath: function () { + this._renderer._updateCircle(this); + }, + + _empty: function () { + return this._radius && !this._renderer._bounds.intersects(this._pxBounds); + }, + + // Needed by the `Canvas` renderer for interactivity + _containsPoint: function (p) { + return p.distanceTo(this._point) <= this._radius + this._clickTolerance(); + } +}); + + +// @factory L.circleMarker(latlng: LatLng, options?: CircleMarker options) +// Instantiates a circle marker object given a geographical point, and an optional options object. +function circleMarker(latlng, options) { + return new CircleMarker(latlng, options); +} + +/* + * @class Circle + * @aka L.Circle + * @inherits CircleMarker + * + * A class for drawing circle overlays on a map. Extends `CircleMarker`. + * + * It's an approximation and starts to diverge from a real circle closer to poles (due to projection distortion). + * + * @example + * + * ```js + * L.circle([50.5, 30.5], {radius: 200}).addTo(map); + * ``` + */ + +var Circle = CircleMarker.extend({ + + initialize: function (latlng, options, legacyOptions) { + if (typeof options === 'number') { + // Backwards compatibility with 0.7.x factory (latlng, radius, options?) + options = extend({}, legacyOptions, {radius: options}); + } + setOptions(this, options); + this._latlng = toLatLng(latlng); + + if (isNaN(this.options.radius)) { throw new Error('Circle radius cannot be NaN'); } + + // @section + // @aka Circle options + // @option radius: Number; Radius of the circle, in meters. + this._mRadius = this.options.radius; + }, + + // @method setRadius(radius: Number): this + // Sets the radius of a circle. Units are in meters. + setRadius: function (radius) { + this._mRadius = radius; + return this.redraw(); + }, + + // @method getRadius(): Number + // Returns the current radius of a circle. Units are in meters. + getRadius: function () { + return this._mRadius; + }, + + // @method getBounds(): LatLngBounds + // Returns the `LatLngBounds` of the path. + getBounds: function () { + var half = [this._radius, this._radiusY || this._radius]; + + return new LatLngBounds( + this._map.layerPointToLatLng(this._point.subtract(half)), + this._map.layerPointToLatLng(this._point.add(half))); + }, + + setStyle: Path.prototype.setStyle, + + _project: function () { + + var lng = this._latlng.lng, + lat = this._latlng.lat, + map = this._map, + crs = map.options.crs; + + if (crs.distance === Earth.distance) { + var d = Math.PI / 180, + latR = (this._mRadius / Earth.R) / d, + top = map.project([lat + latR, lng]), + bottom = map.project([lat - latR, lng]), + p = top.add(bottom).divideBy(2), + lat2 = map.unproject(p).lat, + lngR = Math.acos((Math.cos(latR * d) - Math.sin(lat * d) * Math.sin(lat2 * d)) / + (Math.cos(lat * d) * Math.cos(lat2 * d))) / d; + + if (isNaN(lngR) || lngR === 0) { + lngR = latR / Math.cos(Math.PI / 180 * lat); // Fallback for edge case, #2425 + } + + this._point = p.subtract(map.getPixelOrigin()); + this._radius = isNaN(lngR) ? 0 : p.x - map.project([lat2, lng - lngR]).x; + this._radiusY = p.y - top.y; + + } else { + var latlng2 = crs.unproject(crs.project(this._latlng).subtract([this._mRadius, 0])); + + this._point = map.latLngToLayerPoint(this._latlng); + this._radius = this._point.x - map.latLngToLayerPoint(latlng2).x; + } + + this._updateBounds(); + } +}); + +// @factory L.circle(latlng: LatLng, options?: Circle options) +// Instantiates a circle object given a geographical point, and an options object +// which contains the circle radius. +// @alternative +// @factory L.circle(latlng: LatLng, radius: Number, options?: Circle options) +// Obsolete way of instantiating a circle, for compatibility with 0.7.x code. +// Do not use in new applications or plugins. +function circle(latlng, options, legacyOptions) { + return new Circle(latlng, options, legacyOptions); +} + +/* + * @class Polyline + * @aka L.Polyline + * @inherits Path + * + * A class for drawing polyline overlays on a map. Extends `Path`. + * + * @example + * + * ```js + * // create a red polyline from an array of LatLng points + * var latlngs = [ + * [45.51, -122.68], + * [37.77, -122.43], + * [34.04, -118.2] + * ]; + * + * var polyline = L.polyline(latlngs, {color: 'red'}).addTo(map); + * + * // zoom the map to the polyline + * map.fitBounds(polyline.getBounds()); + * ``` + * + * You can also pass a multi-dimensional array to represent a `MultiPolyline` shape: + * + * ```js + * // create a red polyline from an array of arrays of LatLng points + * var latlngs = [ + * [[45.51, -122.68], + * [37.77, -122.43], + * [34.04, -118.2]], + * [[40.78, -73.91], + * [41.83, -87.62], + * [32.76, -96.72]] + * ]; + * ``` + */ + + +var Polyline = Path.extend({ + + // @section + // @aka Polyline options + options: { + // @option smoothFactor: Number = 1.0 + // How much to simplify the polyline on each zoom level. More means + // better performance and smoother look, and less means more accurate representation. + smoothFactor: 1.0, + + // @option noClip: Boolean = false + // Disable polyline clipping. + noClip: false + }, + + initialize: function (latlngs, options) { + setOptions(this, options); + this._setLatLngs(latlngs); + }, + + // @method getLatLngs(): LatLng[] + // Returns an array of the points in the path, or nested arrays of points in case of multi-polyline. + getLatLngs: function () { + return this._latlngs; + }, + + // @method setLatLngs(latlngs: LatLng[]): this + // Replaces all the points in the polyline with the given array of geographical points. + setLatLngs: function (latlngs) { + this._setLatLngs(latlngs); + return this.redraw(); + }, + + // @method isEmpty(): Boolean + // Returns `true` if the Polyline has no LatLngs. + isEmpty: function () { + return !this._latlngs.length; + }, + + // @method closestLayerPoint(p: Point): Point + // Returns the point closest to `p` on the Polyline. + closestLayerPoint: function (p) { + var minDistance = Infinity, + minPoint = null, + closest = _sqClosestPointOnSegment, + p1, p2; + + for (var j = 0, jLen = this._parts.length; j < jLen; j++) { + var points = this._parts[j]; + + for (var i = 1, len = points.length; i < len; i++) { + p1 = points[i - 1]; + p2 = points[i]; + + var sqDist = closest(p, p1, p2, true); + + if (sqDist < minDistance) { + minDistance = sqDist; + minPoint = closest(p, p1, p2); + } + } + } + if (minPoint) { + minPoint.distance = Math.sqrt(minDistance); + } + return minPoint; + }, + + // @method getCenter(): LatLng + // Returns the center ([centroid](https://en.wikipedia.org/wiki/Centroid)) of the polyline. + getCenter: function () { + // throws error when not yet added to map as this center calculation requires projected coordinates + if (!this._map) { + throw new Error('Must add layer to map before using getCenter()'); + } + + var i, halfDist, segDist, dist, p1, p2, ratio, + points = this._rings[0], + len = points.length; + + if (!len) { return null; } + + // polyline centroid algorithm; only uses the first ring if there are multiple + + for (i = 0, halfDist = 0; i < len - 1; i++) { + halfDist += points[i].distanceTo(points[i + 1]) / 2; + } + + // The line is so small in the current view that all points are on the same pixel. + if (halfDist === 0) { + return this._map.layerPointToLatLng(points[0]); + } + + for (i = 0, dist = 0; i < len - 1; i++) { + p1 = points[i]; + p2 = points[i + 1]; + segDist = p1.distanceTo(p2); + dist += segDist; + + if (dist > halfDist) { + ratio = (dist - halfDist) / segDist; + return this._map.layerPointToLatLng([ + p2.x - ratio * (p2.x - p1.x), + p2.y - ratio * (p2.y - p1.y) + ]); + } + } + }, + + // @method getBounds(): LatLngBounds + // Returns the `LatLngBounds` of the path. + getBounds: function () { + return this._bounds; + }, + + // @method addLatLng(latlng: LatLng, latlngs?: LatLng[]): this + // Adds a given point to the polyline. By default, adds to the first ring of + // the polyline in case of a multi-polyline, but can be overridden by passing + // a specific ring as a LatLng array (that you can earlier access with [`getLatLngs`](#polyline-getlatlngs)). + addLatLng: function (latlng, latlngs) { + latlngs = latlngs || this._defaultShape(); + latlng = toLatLng(latlng); + latlngs.push(latlng); + this._bounds.extend(latlng); + return this.redraw(); + }, + + _setLatLngs: function (latlngs) { + this._bounds = new LatLngBounds(); + this._latlngs = this._convertLatLngs(latlngs); + }, + + _defaultShape: function () { + return isFlat(this._latlngs) ? this._latlngs : this._latlngs[0]; + }, + + // recursively convert latlngs input into actual LatLng instances; calculate bounds along the way + _convertLatLngs: function (latlngs) { + var result = [], + flat = isFlat(latlngs); + + for (var i = 0, len = latlngs.length; i < len; i++) { + if (flat) { + result[i] = toLatLng(latlngs[i]); + this._bounds.extend(result[i]); + } else { + result[i] = this._convertLatLngs(latlngs[i]); + } + } + + return result; + }, + + _project: function () { + var pxBounds = new Bounds(); + this._rings = []; + this._projectLatlngs(this._latlngs, this._rings, pxBounds); + + if (this._bounds.isValid() && pxBounds.isValid()) { + this._rawPxBounds = pxBounds; + this._updateBounds(); + } + }, + + _updateBounds: function () { + var w = this._clickTolerance(), + p = new Point(w, w); + + if (!this._rawPxBounds) { + return; + } + + this._pxBounds = new Bounds([ + this._rawPxBounds.min.subtract(p), + this._rawPxBounds.max.add(p) + ]); + }, + + // recursively turns latlngs into a set of rings with projected coordinates + _projectLatlngs: function (latlngs, result, projectedBounds) { + var flat = latlngs[0] instanceof LatLng, + len = latlngs.length, + i, ring; + + if (flat) { + ring = []; + for (i = 0; i < len; i++) { + ring[i] = this._map.latLngToLayerPoint(latlngs[i]); + projectedBounds.extend(ring[i]); + } + result.push(ring); + } else { + for (i = 0; i < len; i++) { + this._projectLatlngs(latlngs[i], result, projectedBounds); + } + } + }, + + // clip polyline by renderer bounds so that we have less to render for performance + _clipPoints: function () { + var bounds = this._renderer._bounds; + + this._parts = []; + if (!this._pxBounds || !this._pxBounds.intersects(bounds)) { + return; + } + + if (this.options.noClip) { + this._parts = this._rings; + return; + } + + var parts = this._parts, + i, j, k, len, len2, segment, points; + + for (i = 0, k = 0, len = this._rings.length; i < len; i++) { + points = this._rings[i]; + + for (j = 0, len2 = points.length; j < len2 - 1; j++) { + segment = clipSegment(points[j], points[j + 1], bounds, j, true); + + if (!segment) { continue; } + + parts[k] = parts[k] || []; + parts[k].push(segment[0]); + + // if segment goes out of screen, or it's the last one, it's the end of the line part + if ((segment[1] !== points[j + 1]) || (j === len2 - 2)) { + parts[k].push(segment[1]); + k++; + } + } + } + }, + + // simplify each clipped part of the polyline for performance + _simplifyPoints: function () { + var parts = this._parts, + tolerance = this.options.smoothFactor; + + for (var i = 0, len = parts.length; i < len; i++) { + parts[i] = simplify(parts[i], tolerance); + } + }, + + _update: function () { + if (!this._map) { return; } + + this._clipPoints(); + this._simplifyPoints(); + this._updatePath(); + }, + + _updatePath: function () { + this._renderer._updatePoly(this); + }, + + // Needed by the `Canvas` renderer for interactivity + _containsPoint: function (p, closed) { + var i, j, k, len, len2, part, + w = this._clickTolerance(); + + if (!this._pxBounds || !this._pxBounds.contains(p)) { return false; } + + // hit detection for polylines + for (i = 0, len = this._parts.length; i < len; i++) { + part = this._parts[i]; + + for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) { + if (!closed && (j === 0)) { continue; } + + if (pointToSegmentDistance(p, part[k], part[j]) <= w) { + return true; + } + } + } + return false; + } +}); + +// @factory L.polyline(latlngs: LatLng[], options?: Polyline options) +// Instantiates a polyline object given an array of geographical points and +// optionally an options object. You can create a `Polyline` object with +// multiple separate lines (`MultiPolyline`) by passing an array of arrays +// of geographic points. +function polyline(latlngs, options) { + return new Polyline(latlngs, options); +} + +// Retrocompat. Allow plugins to support Leaflet versions before and after 1.1. +Polyline._flat = _flat; + +/* + * @class Polygon + * @aka L.Polygon + * @inherits Polyline + * + * A class for drawing polygon overlays on a map. Extends `Polyline`. + * + * Note that points you pass when creating a polygon shouldn't have an additional last point equal to the first one — it's better to filter out such points. + * + * + * @example + * + * ```js + * // create a red polygon from an array of LatLng points + * var latlngs = [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]]; + * + * var polygon = L.polygon(latlngs, {color: 'red'}).addTo(map); + * + * // zoom the map to the polygon + * map.fitBounds(polygon.getBounds()); + * ``` + * + * You can also pass an array of arrays of latlngs, with the first array representing the outer shape and the other arrays representing holes in the outer shape: + * + * ```js + * var latlngs = [ + * [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]], // outer ring + * [[37.29, -108.58],[40.71, -108.58],[40.71, -102.50],[37.29, -102.50]] // hole + * ]; + * ``` + * + * Additionally, you can pass a multi-dimensional array to represent a MultiPolygon shape. + * + * ```js + * var latlngs = [ + * [ // first polygon + * [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]], // outer ring + * [[37.29, -108.58],[40.71, -108.58],[40.71, -102.50],[37.29, -102.50]] // hole + * ], + * [ // second polygon + * [[41, -111.03],[45, -111.04],[45, -104.05],[41, -104.05]] + * ] + * ]; + * ``` + */ + +var Polygon = Polyline.extend({ + + options: { + fill: true + }, + + isEmpty: function () { + return !this._latlngs.length || !this._latlngs[0].length; + }, + + getCenter: function () { + // throws error when not yet added to map as this center calculation requires projected coordinates + if (!this._map) { + throw new Error('Must add layer to map before using getCenter()'); + } + + var i, j, p1, p2, f, area, x, y, center, + points = this._rings[0], + len = points.length; + + if (!len) { return null; } + + // polygon centroid algorithm; only uses the first ring if there are multiple + + area = x = y = 0; + + for (i = 0, j = len - 1; i < len; j = i++) { + p1 = points[i]; + p2 = points[j]; + + f = p1.y * p2.x - p2.y * p1.x; + x += (p1.x + p2.x) * f; + y += (p1.y + p2.y) * f; + area += f * 3; + } + + if (area === 0) { + // Polygon is so small that all points are on same pixel. + center = points[0]; + } else { + center = [x / area, y / area]; + } + return this._map.layerPointToLatLng(center); + }, + + _convertLatLngs: function (latlngs) { + var result = Polyline.prototype._convertLatLngs.call(this, latlngs), + len = result.length; + + // remove last point if it equals first one + if (len >= 2 && result[0] instanceof LatLng && result[0].equals(result[len - 1])) { + result.pop(); + } + return result; + }, + + _setLatLngs: function (latlngs) { + Polyline.prototype._setLatLngs.call(this, latlngs); + if (isFlat(this._latlngs)) { + this._latlngs = [this._latlngs]; + } + }, + + _defaultShape: function () { + return isFlat(this._latlngs[0]) ? this._latlngs[0] : this._latlngs[0][0]; + }, + + _clipPoints: function () { + // polygons need a different clipping algorithm so we redefine that + + var bounds = this._renderer._bounds, + w = this.options.weight, + p = new Point(w, w); + + // increase clip padding by stroke width to avoid stroke on clip edges + bounds = new Bounds(bounds.min.subtract(p), bounds.max.add(p)); + + this._parts = []; + if (!this._pxBounds || !this._pxBounds.intersects(bounds)) { + return; + } + + if (this.options.noClip) { + this._parts = this._rings; + return; + } + + for (var i = 0, len = this._rings.length, clipped; i < len; i++) { + clipped = clipPolygon(this._rings[i], bounds, true); + if (clipped.length) { + this._parts.push(clipped); + } + } + }, + + _updatePath: function () { + this._renderer._updatePoly(this, true); + }, + + // Needed by the `Canvas` renderer for interactivity + _containsPoint: function (p) { + var inside = false, + part, p1, p2, i, j, k, len, len2; + + if (!this._pxBounds || !this._pxBounds.contains(p)) { return false; } + + // ray casting algorithm for detecting if point is in polygon + for (i = 0, len = this._parts.length; i < len; i++) { + part = this._parts[i]; + + for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) { + p1 = part[j]; + p2 = part[k]; + + if (((p1.y > p.y) !== (p2.y > p.y)) && (p.x < (p2.x - p1.x) * (p.y - p1.y) / (p2.y - p1.y) + p1.x)) { + inside = !inside; + } + } + } + + // also check if it's on polygon stroke + return inside || Polyline.prototype._containsPoint.call(this, p, true); + } + +}); + + +// @factory L.polygon(latlngs: LatLng[], options?: Polyline options) +function polygon(latlngs, options) { + return new Polygon(latlngs, options); +} + +/* + * @class GeoJSON + * @aka L.GeoJSON + * @inherits FeatureGroup + * + * Represents a GeoJSON object or an array of GeoJSON objects. Allows you to parse + * GeoJSON data and display it on the map. Extends `FeatureGroup`. + * + * @example + * + * ```js + * L.geoJSON(data, { + * style: function (feature) { + * return {color: feature.properties.color}; + * } + * }).bindPopup(function (layer) { + * return layer.feature.properties.description; + * }).addTo(map); + * ``` + */ + +var GeoJSON = FeatureGroup.extend({ + + /* @section + * @aka GeoJSON options + * + * @option pointToLayer: Function = * + * A `Function` defining how GeoJSON points spawn Leaflet layers. It is internally + * called when data is added, passing the GeoJSON point feature and its `LatLng`. + * The default is to spawn a default `Marker`: + * ```js + * function(geoJsonPoint, latlng) { + * return L.marker(latlng); + * } + * ``` + * + * @option style: Function = * + * A `Function` defining the `Path options` for styling GeoJSON lines and polygons, + * called internally when data is added. + * The default value is to not override any defaults: + * ```js + * function (geoJsonFeature) { + * return {} + * } + * ``` + * + * @option onEachFeature: Function = * + * A `Function` that will be called once for each created `Feature`, after it has + * been created and styled. Useful for attaching events and popups to features. + * The default is to do nothing with the newly created layers: + * ```js + * function (feature, layer) {} + * ``` + * + * @option filter: Function = * + * A `Function` that will be used to decide whether to include a feature or not. + * The default is to include all features: + * ```js + * function (geoJsonFeature) { + * return true; + * } + * ``` + * Note: dynamically changing the `filter` option will have effect only on newly + * added data. It will _not_ re-evaluate already included features. + * + * @option coordsToLatLng: Function = * + * A `Function` that will be used for converting GeoJSON coordinates to `LatLng`s. + * The default is the `coordsToLatLng` static method. + * + * @option markersInheritOptions: Boolean = false + * Whether default Markers for "Point" type Features inherit from group options. + */ + + initialize: function (geojson, options) { + setOptions(this, options); + + this._layers = {}; + + if (geojson) { + this.addData(geojson); + } + }, + + // @method addData( data ): this + // Adds a GeoJSON object to the layer. + addData: function (geojson) { + var features = isArray(geojson) ? geojson : geojson.features, + i, len, feature; + + if (features) { + for (i = 0, len = features.length; i < len; i++) { + // only add this if geometry or geometries are set and not null + feature = features[i]; + if (feature.geometries || feature.geometry || feature.features || feature.coordinates) { + this.addData(feature); + } + } + return this; + } + + var options = this.options; + + if (options.filter && !options.filter(geojson)) { return this; } + + var layer = geometryToLayer(geojson, options); + if (!layer) { + return this; + } + layer.feature = asFeature(geojson); + + layer.defaultOptions = layer.options; + this.resetStyle(layer); + + if (options.onEachFeature) { + options.onEachFeature(geojson, layer); + } + + return this.addLayer(layer); + }, + + // @method resetStyle( layer? ): this + // Resets the given vector layer's style to the original GeoJSON style, useful for resetting style after hover events. + // If `layer` is omitted, the style of all features in the current layer is reset. + resetStyle: function (layer) { + if (layer === undefined) { + return this.eachLayer(this.resetStyle, this); + } + // reset any custom styles + layer.options = extend({}, layer.defaultOptions); + this._setLayerStyle(layer, this.options.style); + return this; + }, + + // @method setStyle( style ): this + // Changes styles of GeoJSON vector layers with the given style function. + setStyle: function (style) { + return this.eachLayer(function (layer) { + this._setLayerStyle(layer, style); + }, this); + }, + + _setLayerStyle: function (layer, style) { + if (layer.setStyle) { + if (typeof style === 'function') { + style = style(layer.feature); + } + layer.setStyle(style); + } + } +}); + +// @section +// There are several static functions which can be called without instantiating L.GeoJSON: + +// @function geometryToLayer(featureData: Object, options?: GeoJSON options): Layer +// Creates a `Layer` from a given GeoJSON feature. Can use a custom +// [`pointToLayer`](#geojson-pointtolayer) and/or [`coordsToLatLng`](#geojson-coordstolatlng) +// functions if provided as options. +function geometryToLayer(geojson, options) { + + var geometry = geojson.type === 'Feature' ? geojson.geometry : geojson, + coords = geometry ? geometry.coordinates : null, + layers = [], + pointToLayer = options && options.pointToLayer, + _coordsToLatLng = options && options.coordsToLatLng || coordsToLatLng, + latlng, latlngs, i, len; + + if (!coords && !geometry) { + return null; + } + + switch (geometry.type) { + case 'Point': + latlng = _coordsToLatLng(coords); + return _pointToLayer(pointToLayer, geojson, latlng, options); + + case 'MultiPoint': + for (i = 0, len = coords.length; i < len; i++) { + latlng = _coordsToLatLng(coords[i]); + layers.push(_pointToLayer(pointToLayer, geojson, latlng, options)); + } + return new FeatureGroup(layers); + + case 'LineString': + case 'MultiLineString': + latlngs = coordsToLatLngs(coords, geometry.type === 'LineString' ? 0 : 1, _coordsToLatLng); + return new Polyline(latlngs, options); + + case 'Polygon': + case 'MultiPolygon': + latlngs = coordsToLatLngs(coords, geometry.type === 'Polygon' ? 1 : 2, _coordsToLatLng); + return new Polygon(latlngs, options); + + case 'GeometryCollection': + for (i = 0, len = geometry.geometries.length; i < len; i++) { + var layer = geometryToLayer({ + geometry: geometry.geometries[i], + type: 'Feature', + properties: geojson.properties + }, options); + + if (layer) { + layers.push(layer); + } + } + return new FeatureGroup(layers); + + default: + throw new Error('Invalid GeoJSON object.'); + } +} + +function _pointToLayer(pointToLayerFn, geojson, latlng, options) { + return pointToLayerFn ? + pointToLayerFn(geojson, latlng) : + new Marker(latlng, options && options.markersInheritOptions && options); +} + +// @function coordsToLatLng(coords: Array): LatLng +// Creates a `LatLng` object from an array of 2 numbers (longitude, latitude) +// or 3 numbers (longitude, latitude, altitude) used in GeoJSON for points. +function coordsToLatLng(coords) { + return new LatLng(coords[1], coords[0], coords[2]); +} + +// @function coordsToLatLngs(coords: Array, levelsDeep?: Number, coordsToLatLng?: Function): Array +// Creates a multidimensional array of `LatLng`s from a GeoJSON coordinates array. +// `levelsDeep` specifies the nesting level (0 is for an array of points, 1 for an array of arrays of points, etc., 0 by default). +// Can use a custom [`coordsToLatLng`](#geojson-coordstolatlng) function. +function coordsToLatLngs(coords, levelsDeep, _coordsToLatLng) { + var latlngs = []; + + for (var i = 0, len = coords.length, latlng; i < len; i++) { + latlng = levelsDeep ? + coordsToLatLngs(coords[i], levelsDeep - 1, _coordsToLatLng) : + (_coordsToLatLng || coordsToLatLng)(coords[i]); + + latlngs.push(latlng); + } + + return latlngs; +} + +// @function latLngToCoords(latlng: LatLng, precision?: Number|false): Array +// Reverse of [`coordsToLatLng`](#geojson-coordstolatlng) +// Coordinates values are rounded with [`formatNum`](#util-formatnum) function. +function latLngToCoords(latlng, precision) { + latlng = toLatLng(latlng); + return latlng.alt !== undefined ? + [formatNum(latlng.lng, precision), formatNum(latlng.lat, precision), formatNum(latlng.alt, precision)] : + [formatNum(latlng.lng, precision), formatNum(latlng.lat, precision)]; +} + +// @function latLngsToCoords(latlngs: Array, levelsDeep?: Number, closed?: Boolean, precision?: Number|false): Array +// Reverse of [`coordsToLatLngs`](#geojson-coordstolatlngs) +// `closed` determines whether the first point should be appended to the end of the array to close the feature, only used when `levelsDeep` is 0. False by default. +// Coordinates values are rounded with [`formatNum`](#util-formatnum) function. +function latLngsToCoords(latlngs, levelsDeep, closed, precision) { + var coords = []; + + for (var i = 0, len = latlngs.length; i < len; i++) { + coords.push(levelsDeep ? + latLngsToCoords(latlngs[i], levelsDeep - 1, closed, precision) : + latLngToCoords(latlngs[i], precision)); + } + + if (!levelsDeep && closed) { + coords.push(coords[0]); + } + + return coords; +} + +function getFeature(layer, newGeometry) { + return layer.feature ? + extend({}, layer.feature, {geometry: newGeometry}) : + asFeature(newGeometry); +} + +// @function asFeature(geojson: Object): Object +// Normalize GeoJSON geometries/features into GeoJSON features. +function asFeature(geojson) { + if (geojson.type === 'Feature' || geojson.type === 'FeatureCollection') { + return geojson; + } + + return { + type: 'Feature', + properties: {}, + geometry: geojson + }; +} + +var PointToGeoJSON = { + toGeoJSON: function (precision) { + return getFeature(this, { + type: 'Point', + coordinates: latLngToCoords(this.getLatLng(), precision) + }); + } +}; + +// @namespace Marker +// @section Other methods +// @method toGeoJSON(precision?: Number|false): Object +// Coordinates values are rounded with [`formatNum`](#util-formatnum) function with given `precision`. +// Returns a [`GeoJSON`](https://en.wikipedia.org/wiki/GeoJSON) representation of the marker (as a GeoJSON `Point` Feature). +Marker.include(PointToGeoJSON); + +// @namespace CircleMarker +// @method toGeoJSON(precision?: Number|false): Object +// Coordinates values are rounded with [`formatNum`](#util-formatnum) function with given `precision`. +// Returns a [`GeoJSON`](https://en.wikipedia.org/wiki/GeoJSON) representation of the circle marker (as a GeoJSON `Point` Feature). +Circle.include(PointToGeoJSON); +CircleMarker.include(PointToGeoJSON); + + +// @namespace Polyline +// @method toGeoJSON(precision?: Number|false): Object +// Coordinates values are rounded with [`formatNum`](#util-formatnum) function with given `precision`. +// Returns a [`GeoJSON`](https://en.wikipedia.org/wiki/GeoJSON) representation of the polyline (as a GeoJSON `LineString` or `MultiLineString` Feature). +Polyline.include({ + toGeoJSON: function (precision) { + var multi = !isFlat(this._latlngs); + + var coords = latLngsToCoords(this._latlngs, multi ? 1 : 0, false, precision); + + return getFeature(this, { + type: (multi ? 'Multi' : '') + 'LineString', + coordinates: coords + }); + } +}); + +// @namespace Polygon +// @method toGeoJSON(precision?: Number|false): Object +// Coordinates values are rounded with [`formatNum`](#util-formatnum) function with given `precision`. +// Returns a [`GeoJSON`](https://en.wikipedia.org/wiki/GeoJSON) representation of the polygon (as a GeoJSON `Polygon` or `MultiPolygon` Feature). +Polygon.include({ + toGeoJSON: function (precision) { + var holes = !isFlat(this._latlngs), + multi = holes && !isFlat(this._latlngs[0]); + + var coords = latLngsToCoords(this._latlngs, multi ? 2 : holes ? 1 : 0, true, precision); + + if (!holes) { + coords = [coords]; + } + + return getFeature(this, { + type: (multi ? 'Multi' : '') + 'Polygon', + coordinates: coords + }); + } +}); + + +// @namespace LayerGroup +LayerGroup.include({ + toMultiPoint: function (precision) { + var coords = []; + + this.eachLayer(function (layer) { + coords.push(layer.toGeoJSON(precision).geometry.coordinates); + }); + + return getFeature(this, { + type: 'MultiPoint', + coordinates: coords + }); + }, + + // @method toGeoJSON(precision?: Number|false): Object + // Coordinates values are rounded with [`formatNum`](#util-formatnum) function with given `precision`. + // Returns a [`GeoJSON`](https://en.wikipedia.org/wiki/GeoJSON) representation of the layer group (as a GeoJSON `FeatureCollection`, `GeometryCollection`, or `MultiPoint`). + toGeoJSON: function (precision) { + + var type = this.feature && this.feature.geometry && this.feature.geometry.type; + + if (type === 'MultiPoint') { + return this.toMultiPoint(precision); + } + + var isGeometryCollection = type === 'GeometryCollection', + jsons = []; + + this.eachLayer(function (layer) { + if (layer.toGeoJSON) { + var json = layer.toGeoJSON(precision); + if (isGeometryCollection) { + jsons.push(json.geometry); + } else { + var feature = asFeature(json); + // Squash nested feature collections + if (feature.type === 'FeatureCollection') { + jsons.push.apply(jsons, feature.features); + } else { + jsons.push(feature); + } + } + } + }); + + if (isGeometryCollection) { + return getFeature(this, { + geometries: jsons, + type: 'GeometryCollection' + }); + } + + return { + type: 'FeatureCollection', + features: jsons + }; + } +}); + +// @namespace GeoJSON +// @factory L.geoJSON(geojson?: Object, options?: GeoJSON options) +// Creates a GeoJSON layer. Optionally accepts an object in +// [GeoJSON format](https://tools.ietf.org/html/rfc7946) to display on the map +// (you can alternatively add it later with `addData` method) and an `options` object. +function geoJSON(geojson, options) { + return new GeoJSON(geojson, options); +} + +// Backward compatibility. +var geoJson = geoJSON; + +/* + * @class ImageOverlay + * @aka L.ImageOverlay + * @inherits Interactive layer + * + * Used to load and display a single image over specific bounds of the map. Extends `Layer`. + * + * @example + * + * ```js + * var imageUrl = 'https://maps.lib.utexas.edu/maps/historical/newark_nj_1922.jpg', + * imageBounds = [[40.712216, -74.22655], [40.773941, -74.12544]]; + * L.imageOverlay(imageUrl, imageBounds).addTo(map); + * ``` + */ + +var ImageOverlay = Layer.extend({ + + // @section + // @aka ImageOverlay options + options: { + // @option opacity: Number = 1.0 + // The opacity of the image overlay. + opacity: 1, + + // @option alt: String = '' + // Text for the `alt` attribute of the image (useful for accessibility). + alt: '', + + // @option interactive: Boolean = false + // If `true`, the image overlay will emit [mouse events](#interactive-layer) when clicked or hovered. + interactive: false, + + // @option crossOrigin: Boolean|String = false + // Whether the crossOrigin attribute will be added to the image. + // If a String is provided, the image will have its crossOrigin attribute set to the String provided. This is needed if you want to access image pixel data. + // Refer to [CORS Settings](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes) for valid String values. + crossOrigin: false, + + // @option errorOverlayUrl: String = '' + // URL to the overlay image to show in place of the overlay that failed to load. + errorOverlayUrl: '', + + // @option zIndex: Number = 1 + // The explicit [zIndex](https://developer.mozilla.org/docs/Web/CSS/CSS_Positioning/Understanding_z_index) of the overlay layer. + zIndex: 1, + + // @option className: String = '' + // A custom class name to assign to the image. Empty by default. + className: '' + }, + + initialize: function (url, bounds, options) { // (String, LatLngBounds, Object) + this._url = url; + this._bounds = toLatLngBounds(bounds); + + setOptions(this, options); + }, + + onAdd: function () { + if (!this._image) { + this._initImage(); + + if (this.options.opacity < 1) { + this._updateOpacity(); + } + } + + if (this.options.interactive) { + addClass(this._image, 'leaflet-interactive'); + this.addInteractiveTarget(this._image); + } + + this.getPane().appendChild(this._image); + this._reset(); + }, + + onRemove: function () { + remove(this._image); + if (this.options.interactive) { + this.removeInteractiveTarget(this._image); + } + }, + + // @method setOpacity(opacity: Number): this + // Sets the opacity of the overlay. + setOpacity: function (opacity) { + this.options.opacity = opacity; + + if (this._image) { + this._updateOpacity(); + } + return this; + }, + + setStyle: function (styleOpts) { + if (styleOpts.opacity) { + this.setOpacity(styleOpts.opacity); + } + return this; + }, + + // @method bringToFront(): this + // Brings the layer to the top of all overlays. + bringToFront: function () { + if (this._map) { + toFront(this._image); + } + return this; + }, + + // @method bringToBack(): this + // Brings the layer to the bottom of all overlays. + bringToBack: function () { + if (this._map) { + toBack(this._image); + } + return this; + }, + + // @method setUrl(url: String): this + // Changes the URL of the image. + setUrl: function (url) { + this._url = url; + + if (this._image) { + this._image.src = url; + } + return this; + }, + + // @method setBounds(bounds: LatLngBounds): this + // Update the bounds that this ImageOverlay covers + setBounds: function (bounds) { + this._bounds = toLatLngBounds(bounds); + + if (this._map) { + this._reset(); + } + return this; + }, + + getEvents: function () { + var events = { + zoom: this._reset, + viewreset: this._reset + }; + + if (this._zoomAnimated) { + events.zoomanim = this._animateZoom; + } + + return events; + }, + + // @method setZIndex(value: Number): this + // Changes the [zIndex](#imageoverlay-zindex) of the image overlay. + setZIndex: function (value) { + this.options.zIndex = value; + this._updateZIndex(); + return this; + }, + + // @method getBounds(): LatLngBounds + // Get the bounds that this ImageOverlay covers + getBounds: function () { + return this._bounds; + }, + + // @method getElement(): HTMLElement + // Returns the instance of [`HTMLImageElement`](https://developer.mozilla.org/docs/Web/API/HTMLImageElement) + // used by this overlay. + getElement: function () { + return this._image; + }, + + _initImage: function () { + var wasElementSupplied = this._url.tagName === 'IMG'; + var img = this._image = wasElementSupplied ? this._url : create$1('img'); + + addClass(img, 'leaflet-image-layer'); + if (this._zoomAnimated) { addClass(img, 'leaflet-zoom-animated'); } + if (this.options.className) { addClass(img, this.options.className); } + + img.onselectstart = falseFn; + img.onmousemove = falseFn; + + // @event load: Event + // Fired when the ImageOverlay layer has loaded its image + img.onload = bind(this.fire, this, 'load'); + img.onerror = bind(this._overlayOnError, this, 'error'); + + if (this.options.crossOrigin || this.options.crossOrigin === '') { + img.crossOrigin = this.options.crossOrigin === true ? '' : this.options.crossOrigin; + } + + if (this.options.zIndex) { + this._updateZIndex(); + } + + if (wasElementSupplied) { + this._url = img.src; + return; + } + + img.src = this._url; + img.alt = this.options.alt; + }, + + _animateZoom: function (e) { + var scale = this._map.getZoomScale(e.zoom), + offset = this._map._latLngBoundsToNewLayerBounds(this._bounds, e.zoom, e.center).min; + + setTransform(this._image, offset, scale); + }, + + _reset: function () { + var image = this._image, + bounds = new Bounds( + this._map.latLngToLayerPoint(this._bounds.getNorthWest()), + this._map.latLngToLayerPoint(this._bounds.getSouthEast())), + size = bounds.getSize(); + + setPosition(image, bounds.min); + + image.style.width = size.x + 'px'; + image.style.height = size.y + 'px'; + }, + + _updateOpacity: function () { + setOpacity(this._image, this.options.opacity); + }, + + _updateZIndex: function () { + if (this._image && this.options.zIndex !== undefined && this.options.zIndex !== null) { + this._image.style.zIndex = this.options.zIndex; + } + }, + + _overlayOnError: function () { + // @event error: Event + // Fired when the ImageOverlay layer fails to load its image + this.fire('error'); + + var errorUrl = this.options.errorOverlayUrl; + if (errorUrl && this._url !== errorUrl) { + this._url = errorUrl; + this._image.src = errorUrl; + } + }, + + // @method getCenter(): LatLng + // Returns the center of the ImageOverlay. + getCenter: function () { + return this._bounds.getCenter(); + } +}); + +// @factory L.imageOverlay(imageUrl: String, bounds: LatLngBounds, options?: ImageOverlay options) +// Instantiates an image overlay object given the URL of the image and the +// geographical bounds it is tied to. +var imageOverlay = function (url, bounds, options) { + return new ImageOverlay(url, bounds, options); +}; + +/* + * @class VideoOverlay + * @aka L.VideoOverlay + * @inherits ImageOverlay + * + * Used to load and display a video player over specific bounds of the map. Extends `ImageOverlay`. + * + * A video overlay uses the [`