leaflet-exercise-cards.ts 29.8 KB
Newer Older
Tomas Pettersson's avatar
Tomas Pettersson committed
1 2 3 4 5 6 7 8 9
/// <reference path="def/uikit.d.ts" />
/// <reference path="def/leaflet.d.ts" />
/// <reference path="def/moment.d.ts" />
/// <reference path="def/leaflet-forcing-boundary.d.ts" />
/// <reference path="def/reqwest.d.ts" />


class EXLocation extends STWkit.LocationCard {

Tomas Pettersson's avatar
Tomas Pettersson committed
10
    private locationDiv: HTMLDivElement;
Tomas Pettersson's avatar
Tomas Pettersson committed
11
    private locationForm: HTMLFormElement;
Tomas Pettersson's avatar
Tomas Pettersson committed
12 13 14 15 16
    public obsDateInput: HTMLInputElement;
    public obsTimeInput: HTMLInputElement;

    constructor(id, parentDiv, lang, langData, map, forcing, obs, type, initials) {
        var options: any = {};
Tomas Pettersson's avatar
Tomas Pettersson committed
17 18 19 20 21 22 23 24 25 26 27 28
        options['single'] = true;
        options['line'] = true;
        options.polygon = {};
        options['polygon']['show'] = true;
        options['polygon']['name'] = 'Area';
        options['type'] = type;
        options['initials'] = initials;
        super(id, 'Specify time and location', parentDiv, lang, langData, map, forcing, options);

        var self = this;
        var fieldset = <HTMLFieldSetElement>L.DomUtil.create('fieldset', 'uk-margin-top');
        this.locationForm.insertBefore(fieldset, this.locationForm.firstChild);
Tomas Pettersson's avatar
Tomas Pettersson committed
29 30

        var satCallbackFn = function (latlngs, geojsonfeature, timestamp, id) {
Tomas Pettersson's avatar
Tomas Pettersson committed
31
            self.clear();
Tomas Pettersson's avatar
Tomas Pettersson committed
32
            var geojson: any = {};
Tomas Pettersson's avatar
Tomas Pettersson committed
33 34 35 36 37 38 39 40 41 42 43 44 45 46
            geojson["type"] = "FeatureCollection";
            geojson["features"] = [];
            geojson["features"].push(geojsonfeature);
            var observation = {
                "id": id,
                "provider": "EMSA",
                "providerDataRef": null,
                "providerImgRef": null,
                "providerType": null,
                "type": "SAT",
                "date": moment.utc(timestamp).valueOf()
            };
            geojson.features[0].properties["observation"] = [];
            geojson.features[0].properties["observation"].push(observation);
Tomas Pettersson's avatar
Tomas Pettersson committed
47
            geojson.features[0].properties["simulation"] = {};
Tomas Pettersson's avatar
Tomas Pettersson committed
48
            self.populateCard(geojson);
49
            satdetectionHide();
Tomas Pettersson's avatar
Tomas Pettersson committed
50
        };
Tomas Pettersson's avatar
Tomas Pettersson committed
51

Tomas Pettersson's avatar
Tomas Pettersson committed
52 53 54 55 56 57 58 59 60 61 62 63
        function legendBox(fieldset: HTMLFieldSetElement, color, text, size) {
            var rowDiv = <HTMLDivElement>L.DomUtil.create('div', 'uk-form-row uk-margin-remove', fieldset);
            var legendBox = <HTMLDivElement>L.DomUtil.create('div', 'legend-box', rowDiv);
            legendBox.style.backgroundColor = color;
            legendBox.style.width = size;
            legendBox.style.height = size;
            legendBox.title = text;
            var legendText = <HTMLDivElement>L.DomUtil.create('div', 'legend-text', rowDiv);
            legendText.textContent = text;
        }

        if (obs && obs.sat) {
Tomas Pettersson's avatar
Tomas Pettersson committed
64 65
            var obssatRowDiv = <HTMLDivElement>L.DomUtil.create('div', 'uk-form-row', fieldset);
            self.satObs = new Observation.Sat(map, satCallbackFn, 'observation/oo');
Tomas Pettersson's avatar
Tomas Pettersson committed
66 67 68 69 70 71 72 73
            var satDetectionDiv = <HTMLDivElement>L.DomUtil.create('div', '', obssatRowDiv);
            var satDetectionList = <HTMLDListElement>L.DomUtil.create('dl', 'uk-description-list-line', satDetectionDiv);
            var satDetectionItem = <HTMLDListElement>L.DomUtil.create('dt', '', satDetectionList);
            var satDetectionHeading = <HTMLHeadingElement>L.DomUtil.create('h5', 'uk-width-1-1 chevron-title', satDetectionItem);
            satDetectionHeading.textContent = "Satellite oil detections";
            self.satDetectionChevronIcon = <HTMLSpanElement>L.DomUtil.create('span', 'uk-icon-chevron-down chevron-icon', satDetectionHeading);
            self.satDetectionContent = <HTMLDivElement>L.DomUtil.create('div', 'uk-animation-fade', satDetectionItem);
            self.satDetectionContent.style.display = 'none';
Tomas Pettersson's avatar
Tomas Pettersson committed
74
            var satdetectionShow = function () {
Tomas Pettersson's avatar
Tomas Pettersson committed
75 76 77 78
                if (self.satDetectionChevronIcon.classList.contains('uk-icon-chevron-down')) {
                    self.satDetectionChevronIcon.classList.remove('uk-icon-chevron-down');
                    self.satDetectionChevronIcon.classList.add('uk-icon-chevron-up');
                    self.satDetectionContent.style.display = "";
Tomas Pettersson's avatar
Tomas Pettersson committed
79 80
                    self.satObs.show();
                }
81
            }
Tomas Pettersson's avatar
Tomas Pettersson committed
82
            var satdetectionHide = function () {
83
                if (self.satDetectionChevronIcon.classList.contains('uk-icon-chevron-up')) {
Tomas Pettersson's avatar
Tomas Pettersson committed
84 85 86
                    self.satDetectionChevronIcon.classList.remove('uk-icon-chevron-up');
                    self.satDetectionChevronIcon.classList.add('uk-icon-chevron-down');
                    self.satDetectionContent.style.display = 'none';
Tomas Pettersson's avatar
Tomas Pettersson committed
87 88
                    self.satObs.hide();
                }
89 90 91 92
            }


            satDetectionHeading.onclick = function (evt) {
Tomas Pettersson's avatar
Tomas Pettersson committed
93
                if (self.satDetectionChevronIcon.classList.contains('uk-icon-chevron-down'))
94
                    satdetectionShow();
Tomas Pettersson's avatar
Tomas Pettersson committed
95
                else
96
                    satdetectionHide();
Tomas Pettersson's avatar
Tomas Pettersson committed
97
            };
Tomas Pettersson's avatar
Tomas Pettersson committed
98

Tomas Pettersson's avatar
Tomas Pettersson committed
99 100 101 102 103 104
            var satDetectionform = <HTMLFormElement>L.DomUtil.create('form', 'uk-form uk-form-stacked', self.satDetectionContent);
            satDetectionform.onsubmit = function (e) {
                e.preventDefault();
                e.stopPropagation();
                return false;
            };
Tomas Pettersson's avatar
Tomas Pettersson committed
105

Tomas Pettersson's avatar
Tomas Pettersson committed
106 107
            var satDetectionfieldset = <HTMLFieldSetElement>L.DomUtil.create('fieldset', '', satDetectionform);
            var satDetectionRowDiv = <HTMLDivElement>L.DomUtil.create('div', 'uk-form-row uk-margin-top', satDetectionfieldset);
Tomas Pettersson's avatar
Tomas Pettersson committed
108
            super.addLabelDiv(satDetectionRowDiv, "Detection frequency", "See more information <a style='color:#faa732;' href='help/classic/#" + type + "-" + initials + "-satdetection' target='_blank'>here</a>");
Tomas Pettersson's avatar
Tomas Pettersson committed
109 110 111 112 113 114 115 116 117 118 119
            legendBox(satDetectionfieldset, 'rgb(255, 0, 0)', 'Within 24 hours', '10px');
            legendBox(satDetectionfieldset, 'rgb(255, 153, 0)', 'Within 48 hours', '10px');
            legendBox(satDetectionfieldset, 'rgb(255, 255, 0)', 'More than two days ago', '10px');
            legendBox(satDetectionfieldset, 'rgb(255, 255, 255)', 'Older', '10px');

        }

        self.datetimeFormat = 'YYYY-MM-DD HH:mm';
        self.datetimeTFormat = 'YYYY-MM-DDTHH:mm:ss.000';
        self.dateFormat = 'YYYY-MM-DD';
        self.timeFormat = 'HH:mm';
Tomas Pettersson's avatar
Tomas Pettersson committed
120 121
        var obsdateRowDiv = <HTMLDivElement>L.DomUtil.create('div', 'uk-form-row uk-margin-remove', fieldset);
        super.addLabelDiv(obsdateRowDiv, "Observation time (UTC)", "See more information <a style='color:#faa732;' href='help/classic/#" + type + "-" + initials + "-time' target='_blank'>here</a>");
Tomas Pettersson's avatar
Tomas Pettersson committed
122
        var obsdateDiv = <HTMLDivElement>L.DomUtil.create('div', 'uk-form-controls uk-form-icon uk-width-1-1', obsdateRowDiv);
Tomas Pettersson's avatar
Tomas Pettersson committed
123
        obsdateDiv.id = 'guide' + initials + 'date';
Tomas Pettersson's avatar
Tomas Pettersson committed
124 125 126 127 128 129 130
        var obsdateIcon = <HTMLSpanElement>L.DomUtil.create('span', 'uk-icon-calendar', obsdateDiv);
        self.obsDateInput = <HTMLInputElement>L.DomUtil.create('input', 'uk-width-1-2', obsdateDiv);
        self.obsDateInput.type = 'text';
        self.obsDateInput.placeholder = self.dateFormat;
        self.obsTimeInput = <HTMLInputElement>L.DomUtil.create('input', 'uk-width-1-2', obsdateDiv);
        self.obsTimeInput.type = 'text';

Tomas Pettersson's avatar
Tomas Pettersson committed
131 132
        self.obsDateInput.onchange = function () { self.fireChangeFn(self); };
        self.obsTimeInput.onchange = function () { self.fireChangeFn(self); };
Tomas Pettersson's avatar
Tomas Pettersson committed
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160


        UIkit.ready(function () {
            var startDatePicker = UIkit.datepicker(<any>self.obsDateInput, { format: self.dateFormat });
            var startTimePicker = UIkit.timepicker(<any>self.obsTimeInput, {});

            self.defaults();
        });

    }

    public defaults() {
        super.defaults();
        var self = this;
        if (document.body.contains(self.obsDateInput)) {
            if (self.obsDateInput.value == '') {
                var initDate = moment.utc();
                self.obsDateInput.value = initDate.format(self.dateFormat);
                self.obsTimeInput.value = initDate.startOf('hour').format(self.timeFormat);
            }
        }
    }

    public populateCard(geojson) {
        var self = this;
        super.populateCard(geojson);
        var simulation = geojson.features[0].properties.simulation;
        var observation = geojson.features[0].properties.observation[0];
Tomas Pettersson's avatar
Tomas Pettersson committed
161
        var datetime = simulation.startDate;
Tomas Pettersson's avatar
Tomas Pettersson committed
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
        if (geojson.features[0].properties.observation.length > 0) {
            var observation = geojson.features[0].properties.observation[0];
            datetime = observation.date;
        }
        var date = moment.utc(datetime).format(self.dateFormat);
        self.obsDateInput.value = date;
        var time = moment.utc(datetime).format(self.timeFormat);
        self.obsTimeInput.value = time;
        self.fireChangeFn(this);
    }

    public populateData(geojson) {
        super.populateData(geojson);
        var self = this;
        var observation = {
            "id": null,
            "provider": "USER",
            "providerDataRef": null,
            "providerImgRef": null,
            "providerType": null,
            "type": "MANUAL",
            "date": moment.utc(self.obsDateInput.value + ' ' + self.obsTimeInput.value, self.datetimeFormat).valueOf()

        };
Tomas Pettersson's avatar
Tomas Pettersson committed
186
        geojson.features[0].properties["primary"] = 'PADM';        
Tomas Pettersson's avatar
Tomas Pettersson committed
187 188
        geojson.features[0].properties["observation"] = [];
        geojson.features[0].properties["observation"].push(observation);
Tomas Pettersson's avatar
Tomas Pettersson committed
189
    }
Tomas Pettersson's avatar
Tomas Pettersson committed
190
}
Tomas Pettersson's avatar
Tomas Pettersson committed
191

Tomas Pettersson's avatar
Tomas Pettersson committed
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209

class EXAmount extends STWkit.AccordionCard {
    public oncallback: Function;
    public amountInput: HTMLInputElement;
    public amountSelect: HTMLSelectElement;
    public nextButton: any;

    constructor(id, parentDiv, lang, map, type, initials) {
        var amountDiv = <HTMLDivElement>L.DomUtil.create('div', 'uk-width-1-1 uk-margin-top', parentDiv);
        super(id, 'Amount', parentDiv, amountDiv);
        var self = this;
        var form = <HTMLFormElement>L.DomUtil.create('form', 'uk-form uk-form-stacked', amountDiv);
        form.setAttribute('novalidate', '');
        form.onsubmit = function (e) {
            e.preventDefault();
            e.stopPropagation();
            return false;
        };
Tomas Pettersson's avatar
Tomas Pettersson committed
210 211
        form.onkeypress = function (e) {
            var key = e.charCode || e.keyCode || 0;
Tomas Pettersson's avatar
Tomas Pettersson committed
212
            if (key == 13) e.preventDefault();
Tomas Pettersson's avatar
Tomas Pettersson committed
213
        };
Tomas Pettersson's avatar
Tomas Pettersson committed
214 215 216 217 218 219 220 221 222 223

        function addOption(parent, value, txt) {
            var option = <HTMLOptionElement>L.DomUtil.create('option', '', parent);
            option.value = value;
            option.textContent = txt;
        }


        var fieldset = <HTMLFieldSetElement>L.DomUtil.create('fieldset', '', form);
        var amountRowDiv: any = <HTMLDivElement>L.DomUtil.create('div', 'uk-form-row', fieldset);
Tomas Pettersson's avatar
Tomas Pettersson committed
224
        amountRowDiv.id = 'guide' + initials + 'amountvalue';
Tomas Pettersson's avatar
Tomas Pettersson committed
225 226 227 228 229
        amountRowDiv.guideFn = function () {
            self.amountInput.value = '10';
            validate();
        }

Tomas Pettersson's avatar
Tomas Pettersson committed
230
        super.addLabelDiv(amountRowDiv, "Amount", "See more information <a style='color:#faa732;' href='help/classic/#" + type + "-" + initials + "-amount' target='_blank'>here</a>");
Tomas Pettersson's avatar
Tomas Pettersson committed
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
        var amountValueDiv = <HTMLDivElement>L.DomUtil.create('div', 'uk-width-1-1', amountRowDiv);
        self.amountInput = <HTMLInputElement>L.DomUtil.create('input', 'uk-width-1-4', amountValueDiv);
        self.amountInput.type = 'number';
        self.amountInput.step = '10';
        self.amountInput.min = '0';
        var amountUnitDiv = <HTMLDivElement>L.DomUtil.create('div', 'uk-width-1-2 uk-form-select select', amountValueDiv);
        amountUnitDiv.setAttribute('data-uk-form-select', '');
        var selectedAmountUnit = <HTMLSpanElement>L.DomUtil.create('span', '', amountUnitDiv);
        self.amountSelect = <HTMLSelectElement>L.DomUtil.create('select', '', amountUnitDiv);
        addOption(self.amountSelect, 'm3', '');
        addOption(self.amountSelect, 'tonnes', 'tonnes');


        self.amountInput.onchange = function () {
            validate();
        };

        function validate() {
            var amountValue = parseInt(self.amountInput.value);
            var amountOk = false;
            if (amountValue > 0) amountOk = true;
            if (amountOk) {
                self.status = true;
                STWkit.AccordionCard.enableNext(self.nextButton, true);
                (self.oncallback && self.oncallback());
            } else {
                self.clear();
            }
        };


        var clearDiv = <HTMLDivElement>L.DomUtil.create('div', 'uk-clearfix', amountDiv);
        var clearButton = <HTMLButtonElement>L.DomUtil.create('button', 'uk-button uk-margin-top uk-align-left', clearDiv);
        clearButton.textContent = 'Clear';
        clearButton.onclick = function () {
            self.clear();
        };
        self.nextButton = <HTMLButtonElement>L.DomUtil.create('button', 'uk-button uk-margin-top uk-align-right', clearDiv);
Tomas Pettersson's avatar
Tomas Pettersson committed
269
        self.nextButton.id = 'guide' + initials + 'amount';
Tomas Pettersson's avatar
Tomas Pettersson committed
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
        self.nextButton.textContent = 'Next';
        self.nextButton.guideFn = function () {
            self.nextButton.click();
        }
        STWkit.AccordionCard.enableNext(self.nextButton, false);
        self.nextButton.onclick = function () {
            if (!STWkit.AccordionCard.isEnabled(self.nextButton)) {
                STWkit.AccordionCard.warningMsg('Mandatory fields missing',
                    'Specify a valid <b>amount</b>.');
                return;
            }

            (self.oncallback && self.oncallback(true));
        };

        UIkit.ready(function () {
            self.defaults();
        });
    }

    public defaults() {
        var self = this;
    }
    public populateCard(geojson) {
        var self = this;
        var simulation = geojson.features[0].properties.simulation;
Tomas Pettersson's avatar
Tomas Pettersson committed
296

Tomas Pettersson's avatar
Tomas Pettersson committed
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
        self.amountInput.value = simulation.amount;
        var amountevt = document.createEvent('Event');
        amountevt.initEvent("change", true, true);
        self.amountInput.dispatchEvent(amountevt);
        self.amountSelect.value = simulation.amountUnit;
    }

    public populateData(geojson) {
        var self = this;
        geojson.features[0].properties["simulation"]["amount"] = self.amountInput.value;
        geojson.features[0].properties["simulation"]["amountUnit"] = self.amountSelect.options[self.amountSelect.selectedIndex].value;
    }


    public clear() {
        var self = this;
        super.clear();
        self.amountInput.value = '';
        STWkit.AccordionCard.enableNext(self.nextButton, false);
        self.status = false;
        (self.oncallback && self.oncallback());
    }
Tomas Pettersson's avatar
Tomas Pettersson committed
319 320 321
}


Tomas Pettersson's avatar
Tomas Pettersson committed
322 323 324 325 326
class TrajectoryLineHandler extends LineHandler {

    private _errorShown : any;
    private _mouseDownOrigin : any;
    private time : any;
Tomas Pettersson's avatar
Tomas Pettersson committed
327 328 329 330 331 332 333
    private _map : any;
    private _currentLatLng: any;
    private _enabled: any;
    private _mouseMarker: any;
    private _clickHandled: any;
    private _disableMarkers: any;

Tomas Pettersson's avatar
Tomas Pettersson committed
334 335
    constructor(time, map, options){
        super(map,options);
Tomas Pettersson's avatar
Tomas Pettersson committed
336 337 338 339 340
        if (time )this.time = time.reverse();
    }

    private resetTime(time){
        this.time = time.reverse();
Tomas Pettersson's avatar
Tomas Pettersson committed
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
    }

    private autoPoint(e, latlng) {
        if (this._errorShown)
            return;

        if (this._mouseDownOrigin) {
            var originalEvent = e.originalEvent;
            //if(originalEvent.button == 2) {
            var distance = L.point(originalEvent.clientX, originalEvent.clientY)
                .distanceTo(this._mouseDownOrigin);

            //if (Math.abs(distance) < 9 * (window.devicePixelRatio || 1)) {
            if (Math.abs(distance) > 6 * (window.devicePixelRatio || 1)) {
                if (this.time.length > 0) {
Tomas Pettersson's avatar
Tomas Pettersson committed
356
                    (<any>L).drawLocal.draw.handlers.polyline.tooltip.cont = moment.utc(this.time.pop()).format('YYYY-MM-DD HH:mm')+' ('+this.time.length+' left)';                                        
Tomas Pettersson's avatar
Tomas Pettersson committed
357 358
                    super.addVertex(latlng);
                    this._mouseDownOrigin = L.point(originalEvent.clientX, originalEvent.clientY);
Tomas Pettersson's avatar
Tomas Pettersson committed
359 360 361 362 363 364
                } else {
                    super._finishShape();
                    this._mouseDownOrigin = null;
                    this._clickHandled = false;
                    this._disableMarkers = false;                    
                    return;
Tomas Pettersson's avatar
Tomas Pettersson committed
365 366 367 368 369
                }
            }
            //}
        }
    };
Tomas Pettersson's avatar
Tomas Pettersson committed
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
    private _onMouseMove(e) {
        var newPos = this._map.mouseEventToLayerPoint(e.originalEvent);
        var latlng = this._map.layerPointToLatLng(newPos);

        // Save latlng
        // should this be moved to _updateGuide() ?
        this._currentLatLng = latlng;

        super._updateTooltip(latlng);

        if (e.originalEvent.ctrlKey) {
            super.deleteLastVertex(e);
        }
        else {
            this.autoPoint(e, latlng);
        }
        if (this._enabled) {
            // Update the guide line
            super._updateGuide(newPos);
Tomas Pettersson's avatar
Tomas Pettersson committed
389
    
Tomas Pettersson's avatar
Tomas Pettersson committed
390 391 392
            // Update the mouse marker position
            this._mouseMarker.setLatLng(latlng);
        }
Tomas Pettersson's avatar
Tomas Pettersson committed
393

Tomas Pettersson's avatar
Tomas Pettersson committed
394 395 396
        L.DomEvent.preventDefault(e.originalEvent);
        L.DomEvent.stopPropagation(e.originalEvent);
    };
Tomas Pettersson's avatar
Tomas Pettersson committed
397

Tomas Pettersson's avatar
Tomas Pettersson committed
398
}
Tomas Pettersson's avatar
Tomas Pettersson committed
399

Tomas Pettersson's avatar
Tomas Pettersson committed
400 401 402
class EXTrajectory extends STWkit.AccordionCard {
    public oncallback: Function;
    public lineButton: HTMLButtonElement;
Tomas Pettersson's avatar
Tomas Pettersson committed
403 404
    private lineHandler : any;    
    private trajectoryLayer : L.GeoJSON;
Tomas Pettersson's avatar
Tomas Pettersson committed
405 406
    private trajectoryLabelLayer : any;
    private trajMarkerArray : any;
Tomas Pettersson's avatar
Tomas Pettersson committed
407 408
    public exitControl: L.Control;
    public positions: any[];    
Tomas Pettersson's avatar
Tomas Pettersson committed
409 410
    private map: any;    
    private time: any;    
Tomas Pettersson's avatar
Tomas Pettersson committed
411 412 413 414 415 416
    public nextButton: any;

    constructor(id, parentDiv, lang, langData, map, type, initials) {
        var trajectoryDiv = <HTMLDivElement>L.DomUtil.create('div', 'uk-width-1-1 uk-margin-top', parentDiv);
        super(id, 'Trajectory', parentDiv, trajectoryDiv);
        var self = this;
Tomas Pettersson's avatar
Tomas Pettersson committed
417
        this.map = map;
Tomas Pettersson's avatar
Tomas Pettersson committed
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
        var form = <HTMLFormElement>L.DomUtil.create('form', 'uk-form uk-form-stacked', trajectoryDiv);
        form.setAttribute('novalidate', '');
        form.onsubmit = function (e) {
            e.preventDefault();
            e.stopPropagation();
            return false;
        };
        form.onkeypress = function (e) {
            var key = e.charCode || e.keyCode || 0;
            if (key == 13) e.preventDefault();
        };
        self.positions = [];
        var positionLabelGrid = <HTMLDivElement>L.DomUtil.create('div', 'uk-grid uk-margin-top', form);
        var positionlabelDiv = <HTMLDivElement>L.DomUtil.create('div', 'uk-width-1-1', positionLabelGrid);
        super.addLabelDiv(positionlabelDiv, "Position", "See more information <a style='color:#faa732;' href='help/classic/#" + type + "-" + initials + "-position' target='_blank'>here</a>");
        var positionDiv: any = <HTMLDivElement>L.DomUtil.create('div', '', form);
        positionDiv.id = 'guide' + initials + 'pos';
        var positionButtonGrid = <HTMLDivElement>L.DomUtil.create('div', 'uk-grid uk-grid-small', positionDiv);
        var drawDiv = <HTMLDivElement>L.DomUtil.create('div', 'uk-width-1-2', positionButtonGrid);
        var drawButton = <HTMLButtonElement>L.DomUtil.create('button', 'uk-button uk-button-small uk-align-left uk-margin-remove', drawDiv);
        drawButton.textContent = 'Free hand draw';


        positionDiv.guideFn = function () {
            var geojson = {};
            geojson["type"] = "FeatureCollection";
            geojson["features"] = [];
            var feature = {};
            feature['type'] = "Feature";
            feature['geometry'] = {};
            feature['geometry']['type'] = "Point";
            feature['geometry']['coordinates'] = [];
            // feature['geometry']['coordinates'].push(19.0);
            // feature['geometry']['coordinates'].push(56.0);
            geojson["features"].push(feature);
Tomas Pettersson's avatar
Tomas Pettersson committed
453
            // self.control.addGeoJSON(geojson);
Tomas Pettersson's avatar
Tomas Pettersson committed
454
        }
Tomas Pettersson's avatar
Tomas Pettersson committed
455

Tomas Pettersson's avatar
Tomas Pettersson committed
456
        var color = '#CA5A1B';
Tomas Pettersson's avatar
Tomas Pettersson committed
457
        this.lineHandler = new TrajectoryLineHandler(null, map, {
Tomas Pettersson's avatar
Tomas Pettersson committed
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
            allowIntersection: true,   
            icon: new L.DivIcon({
                        iconSize: new L.Point(8, 8),
                        className: 'leaflet-div-icon leaflet-editing-icon'
                    }),                                      
            drawError: {
                color: color,
                timeout: 1000
            },
            shapeOptions: {
                color: color
            },
            showArea: true,
            metric: true,
            repeatMode : false
Tomas Pettersson's avatar
Tomas Pettersson committed
473
        });
Tomas Pettersson's avatar
Tomas Pettersson committed
474 475
        this.lineHandler.type = 'draw'+id;      
        
Tomas Pettersson's avatar
Tomas Pettersson committed
476 477 478 479 480 481 482 483


        map.on('zoomend', function () {
            if (self.map.hasLayer(self.trajectoryLabelLayer)) {
                self.updateTrajectoryLabelLayer();
            }
        });        
        
Tomas Pettersson's avatar
Tomas Pettersson committed
484 485 486 487
        map.on('draw:created', function (e) {
            var type = e.layerType,
                layer = e.layer;
            if (type == 'draw'+id) {
Tomas Pettersson's avatar
Tomas Pettersson committed
488 489
                var trajlinefeature = layer.toGeoJSON();
                if ((trajlinefeature.geometry) && (trajlinefeature.geometry.coordinates.length  == self.time.length)) {
Tomas Pettersson's avatar
Tomas Pettersson committed
490
                    self.trajectoryLayer.addData(trajlinefeature);
Tomas Pettersson's avatar
Tomas Pettersson committed
491 492 493 494 495 496 497 498 499 500 501 502 503
                    var trajpointjson: any = STWkit.featurecollection();
                    for (var i = 0; i < self.time.length; i++) {
                        var trajpointfeature: any = STWkit.createFeature("Point");
                        trajpointfeature.geometry.coordinates = trajlinefeature.geometry.coordinates[i];
                        trajpointfeature.properties.time = self.time[i];
                        if (i == 0) trajpointfeature.properties.start = true;
                        if (i == self.time.length - 1) trajpointfeature.properties.end = true;
                        trajpointjson.features.push(trajpointfeature);
                    }
                    self.trajectoryLabelLayer.addData(trajpointjson);    
                    self.updateTrajectoryLabelLayer();
                    
                }
Tomas Pettersson's avatar
Tomas Pettersson committed
504 505 506 507 508 509 510 511
                var toggleevt = document.createEvent("CustomEvent");
                toggleevt.initCustomEvent('container:toggleVisibility', false, false, {
                    'show': true
                });
                window.dispatchEvent(toggleevt);
                self.fireChangeFn(self);
                if (self.exitControl) map.removeControl(self.exitControl);
                self.exitControl = null;
Tomas Pettersson's avatar
Tomas Pettersson committed
512 513 514 515 516
                if (self.getLatLngArray().length > 0) {
                    self.status = true;
                    STWkit.AccordionCard.enableNext(self.nextButton, true);
                    (self.oncallback && self.oncallback());
                }
Tomas Pettersson's avatar
Tomas Pettersson committed
517 518

            }
Tomas Pettersson's avatar
Tomas Pettersson committed
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
        });             
        this.trajectoryLayer = new L.GeoJSON(null, {});
        this.trajMarkerArray = [];
        this.trajectoryLabelLayer = L.geoJson(null, {
            'pointToLayer': function (feature: any, latlng: L.LatLng) {
                var iconOpts: any = {
                    iconSize: [25, 41],
                    iconAnchor: [40, 61],
                    className: 'iconHiddentextIcon',
                    clickable: false,
                    html: '<span class="trajLabel">' + moment.utc(feature.properties.time).format('YYYY-MM-DD HH:mm') + ' [' + STWkit.convertDDtoDDM(latlng.lat, true) + ', ' + STWkit.convertDDtoDDM(latlng.lng, false) + '] </span>'
                };
                var marker: any = L.marker(latlng, {
                    clickable: false,
                    icon: L.divIcon(iconOpts)
                }
                );
                marker.visible = true;
                self.trajMarkerArray.push(marker);
Tomas Pettersson's avatar
Tomas Pettersson committed
538
                return marker;
Tomas Pettersson's avatar
Tomas Pettersson committed
539 540
            }
        });
Tomas Pettersson's avatar
Tomas Pettersson committed
541
        
Tomas Pettersson's avatar
Tomas Pettersson committed
542 543
        map.addLayer(this.trajectoryLayer);  
        map.addLayer(this.trajectoryLabelLayer);  
Tomas Pettersson's avatar
Tomas Pettersson committed
544 545

        drawButton.onclick = function () {
Tomas Pettersson's avatar
Tomas Pettersson committed
546
            self.clear();
Tomas Pettersson's avatar
Tomas Pettersson committed
547 548 549 550 551
            var toggleevt = document.createEvent("CustomEvent");
            toggleevt.initCustomEvent('container:toggleVisibility', false, false, {
                'show': false
            });
            window.dispatchEvent(toggleevt);
Tomas Pettersson's avatar
Tomas Pettersson committed
552 553

            self.lineHandler.enable();
Tomas Pettersson's avatar
Tomas Pettersson committed
554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612
            self.exitControl = new L.Control({ position: 'bottomright' });
            self.exitControl.onAdd = function (map: L.Map) {
                var container = L.DomUtil.create('div', 'exit-control');
                var exitPanel = L.DomUtil.create('div', 'uk-panel uk-panel-box', container);
                var finishButton = <HTMLButtonElement>L.DomUtil.create('button', 'uk-button uk-button-small uk-button-primary uk-margin-right', exitPanel);
                finishButton.textContent = 'Finish';
                finishButton.onclick = function (e) {
                    map.fire('draw:canceled');
                };
                finishButton.style.display = 'none';
                var cancelButton = <HTMLButtonElement>L.DomUtil.create('button', 'uk-button uk-button-small', exitPanel);
                cancelButton.textContent = 'Cancel';
                cancelButton.onclick = function (e) {
                    if (self.exitControl) map.removeControl(self.exitControl);
                    self.exitControl = null;
                    var toggleevt = document.createEvent("CustomEvent");
                    toggleevt.initCustomEvent('container:toggleVisibility', false, false, {
                        'show': true
                    });
                    window.dispatchEvent(toggleevt);
                    self.clear();
                };

                L.DomEvent.disableClickPropagation(container);
                return container;
            };
            self.exitControl.addTo(map);

        };


        var clearDiv = <HTMLDivElement>L.DomUtil.create('div', 'uk-clearfix', trajectoryDiv);
        var clearButton = <HTMLButtonElement>L.DomUtil.create('button', 'uk-button uk-margin-top uk-align-left', clearDiv);
        clearButton.textContent = 'Clear';
        clearButton.onclick = function () {
            self.clear();
        };
        self.nextButton = <HTMLButtonElement>L.DomUtil.create('button', 'uk-button uk-margin-top uk-align-right', clearDiv);
        self.nextButton.id = 'guide' + initials + 'trajectory';
        self.nextButton.textContent = 'Next';
        self.nextButton.guideFn = function () {
            self.nextButton.click();
        }
        STWkit.AccordionCard.enableNext(self.nextButton, false);
        self.nextButton.onclick = function () {
            if (!STWkit.AccordionCard.isEnabled(self.nextButton)) {
                STWkit.AccordionCard.warningMsg('Mandatory fields missing',
                    'Specify a valid <b>position</b>.');
                return;
            }

            (self.oncallback && self.oncallback(true));
        };

        UIkit.ready(function () {
            self.defaults();
        });
    }

Tomas Pettersson's avatar
Tomas Pettersson committed
613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664
    public changeFn(changeCard) {
        var self = this;
        if ((typeof changeCard.from !== 'undefined') && (typeof changeCard.to !== 'undefined')) {
            var from = changeCard.from;
            var to = changeCard.to;
            if (from.isBefore(to)) {
                self.time = [];
                self.time.push(from.valueOf());
                var t = from;
                while (t.isBefore(to)) {
                    t = t.add(15,'m');
                    self.time.push(t.valueOf());
                }
            }
        }
    }



    private updateTrajectoryLabelLayer() {
        var self = this;
        if (self.trajMarkerArray.length > 2) {
            var occupied = new Array();
            occupied[0] = STWkit.getRectangle(self.map.latLngToLayerPoint(self.trajMarkerArray[0]._latlng));
            occupied[1] = STWkit.getRectangle(self.map.latLngToLayerPoint(self.trajMarkerArray[self.trajMarkerArray.length - 1]._latlng));
            var k = 2;
            for (var i = 1; i < self.trajMarkerArray.length - 1; i++) {
                var rect = STWkit.getRectangle(self.map.latLngToLayerPoint(self.trajMarkerArray[i]._latlng));
                var ok = true;
                for (var j = 0; j < occupied.length; j++) {
                    if (STWkit.intersect(rect, occupied[j])) {
                        ok = false;
                        break;
                    }
                }
                if (ok) {
                    occupied[k] = STWkit.getRectangle(self.map.latLngToLayerPoint(self.trajMarkerArray[i]._latlng));
                    k++;
                    if (!self.trajMarkerArray[i].visible) {
                        self.trajectoryLabelLayer.addLayer(self.trajMarkerArray[i]);
                        self.trajMarkerArray[i].visible = true;
                    }
                } else {
                    if (self.trajMarkerArray[i].visible) {
                        self.trajectoryLabelLayer.removeLayer(self.trajMarkerArray[i]);
                        self.trajMarkerArray[i].visible = false;
                    }
                }
            }
        }
    };

Tomas Pettersson's avatar
Tomas Pettersson committed
665 666 667 668 669 670 671 672 673
    private getLatLngArray() {
        var self = this;
        var latlngs = [];
        self.trajectoryLayer.getLayers().forEach (function (layer:any) {
            if (layer._latlngs) latlngs.push(layer._latlngs); else latlngs.push([layer._latlng]);
         });
        return latlngs;    
    }

Tomas Pettersson's avatar
Tomas Pettersson committed
674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690
    public validate() {
        if (this.positions.length == 0) return;
        this.status = true;
        STWkit.AccordionCard.enableNext(this.nextButton, true);
        (this.oncallback && this.oncallback());
    };


    public defaults() {
        var self = this;
    }
    public populateCard(geojson) {
        var self = this;
    }

    public populateData(geojson) {
        var self = this;
Tomas Pettersson's avatar
Tomas Pettersson committed
691 692 693 694 695 696 697 698 699 700 701 702
        var feature = STWkit.createFeature('LineString');
        var props = feature.properties;
        props['auxiliary'] = 'exercise';
        props['time'] = self.time;
        var coords = feature.geometry.coordinates;
        var latlngs:Array<L.LatLng> = self.getLatLngArray()[0];
        for (let i = 0; i < latlngs.length; i++) {
            const latlng = latlngs[i];
            coords.push([latlng.lng, latlng.lat]);
        }
        geojson.features.push(feature);

Tomas Pettersson's avatar
Tomas Pettersson committed
703 704 705 706 707 708
    }


    public clear() {
        var self = this;
        super.clear();
Tomas Pettersson's avatar
Tomas Pettersson committed
709 710 711
        self.trajectoryLabelLayer.clearLayers();
        self.trajectoryLayer.clearLayers()
        self.trajMarkerArray = [];
Tomas Pettersson's avatar
Tomas Pettersson committed
712
        if (self.lineHandler._enabled) self.lineHandler.disable();
Tomas Pettersson's avatar
Tomas Pettersson committed
713
        self.lineHandler.resetTime(self.time.slice(0));
Tomas Pettersson's avatar
Tomas Pettersson committed
714 715 716 717 718 719
        if (self.nextButton) STWkit.AccordionCard.enableNext(self.nextButton, false);
        (self.oncallback && self.oncallback());
    }
}