leaflet-exercise-cards.ts 34.1 KB
Newer Older
Tomas Pettersson's avatar
Tomas Pettersson committed
1 2 3 4
/// <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" />
5 6 7
/// <reference path="def/reqwest.d.ts" />import { GeoJSON } from "leaflet";


Tomas Pettersson's avatar
Tomas Pettersson committed
8 9 10 11


class EXLocation extends STWkit.LocationCard {

Tomas Pettersson's avatar
Tomas Pettersson committed
12
    private locationDiv: HTMLDivElement;
Tomas Pettersson's avatar
Tomas Pettersson committed
13
    private locationForm: HTMLFormElement;
Tomas Pettersson's avatar
Tomas Pettersson committed
14 15
    public obsDateInput: HTMLInputElement;
    public obsTimeInput: HTMLInputElement;
16 17 18
    private type: string;
    private subtype: string;                

Tomas Pettersson's avatar
Tomas Pettersson committed
19

20
    constructor(id, parentDiv, lang, langData, map, forcing, obs, type, subtype, initials) {
Tomas Pettersson's avatar
Tomas Pettersson committed
21
        var options: any = {};
Tomas Pettersson's avatar
Tomas Pettersson committed
22 23 24 25 26 27 28 29 30 31
        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;
32 33
        self.type = type;
        self.subtype = subtype;
Tomas Pettersson's avatar
Tomas Pettersson committed
34 35
        var fieldset = <HTMLFieldSetElement>L.DomUtil.create('fieldset', 'uk-margin-top');
        this.locationForm.insertBefore(fieldset, this.locationForm.firstChild);
Tomas Pettersson's avatar
Tomas Pettersson committed
36 37

        var satCallbackFn = function (latlngs, geojsonfeature, timestamp, id) {
Tomas Pettersson's avatar
Tomas Pettersson committed
38
            self.clear();
Tomas Pettersson's avatar
Tomas Pettersson committed
39
            var geojson: any = {};
Tomas Pettersson's avatar
Tomas Pettersson committed
40 41 42 43 44 45 46 47 48 49 50 51 52 53
            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
54
            geojson.features[0].properties["simulation"] = {};
Tomas Pettersson's avatar
Tomas Pettersson committed
55
            self.populateCard(geojson);
56
            satdetectionHide();
Tomas Pettersson's avatar
Tomas Pettersson committed
57
        };
Tomas Pettersson's avatar
Tomas Pettersson committed
58

Tomas Pettersson's avatar
Tomas Pettersson committed
59 60 61 62 63 64 65 66 67 68 69 70
        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
71 72
            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
73 74 75 76 77 78 79 80
            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
81
            var satdetectionShow = function () {
Tomas Pettersson's avatar
Tomas Pettersson committed
82 83 84 85
                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
86 87
                    self.satObs.show();
                }
88
            }
Tomas Pettersson's avatar
Tomas Pettersson committed
89
            var satdetectionHide = function () {
90
                if (self.satDetectionChevronIcon.classList.contains('uk-icon-chevron-up')) {
Tomas Pettersson's avatar
Tomas Pettersson committed
91 92 93
                    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
94 95
                    self.satObs.hide();
                }
96 97 98 99
            }


            satDetectionHeading.onclick = function (evt) {
Tomas Pettersson's avatar
Tomas Pettersson committed
100
                if (self.satDetectionChevronIcon.classList.contains('uk-icon-chevron-down'))
101
                    satdetectionShow();
Tomas Pettersson's avatar
Tomas Pettersson committed
102
                else
103
                    satdetectionHide();
Tomas Pettersson's avatar
Tomas Pettersson committed
104
            };
Tomas Pettersson's avatar
Tomas Pettersson committed
105

Tomas Pettersson's avatar
Tomas Pettersson committed
106 107 108 109 110 111
            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
112

Tomas Pettersson's avatar
Tomas Pettersson committed
113 114
            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
115
            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
116 117 118 119 120 121 122 123 124 125 126
            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
127 128
        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
129
        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
130
        obsdateDiv.id = 'guide' + initials + 'date';
Tomas Pettersson's avatar
Tomas Pettersson committed
131 132 133 134 135 136 137
        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
138 139
        self.obsDateInput.onchange = function () { self.fireChangeFn(self); };
        self.obsTimeInput.onchange = function () { self.fireChangeFn(self); };
Tomas Pettersson's avatar
Tomas Pettersson committed
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167


        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
168
        var datetime = simulation.startDate;
Tomas Pettersson's avatar
Tomas Pettersson committed
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
        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()

        };
193 194 195
        var layer:any = L.GeoJSON.geometryToLayer(geojson.features[0]);
        var center = null;
        if (layer._latlng) center = layer._latlng; else center = layer.getBounds().getCenter()
Tomas Pettersson's avatar
Tomas Pettersson committed
196
        geojson.features[0].properties["primary"] = 'PADM';        
197 198 199 200
        geojson.features[0].properties["type"] = self.type;        
        geojson.features[0].properties["subtype"] = self.subtype;        
        geojson.features[0].properties["meanLat"] = center.lat;        
        geojson.features[0].properties["meanLng"] = center.lng;        
Tomas Pettersson's avatar
Tomas Pettersson committed
201 202
        geojson.features[0].properties["observation"] = [];
        geojson.features[0].properties["observation"].push(observation);
Tomas Pettersson's avatar
Tomas Pettersson committed
203
    }
Tomas Pettersson's avatar
Tomas Pettersson committed
204
}
Tomas Pettersson's avatar
Tomas Pettersson committed
205

Tomas Pettersson's avatar
Tomas Pettersson committed
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223

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
224 225
        form.onkeypress = function (e) {
            var key = e.charCode || e.keyCode || 0;
Tomas Pettersson's avatar
Tomas Pettersson committed
226
            if (key == 13) e.preventDefault();
Tomas Pettersson's avatar
Tomas Pettersson committed
227
        };
Tomas Pettersson's avatar
Tomas Pettersson committed
228 229 230 231 232 233 234 235 236 237

        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
238
        amountRowDiv.id = 'guide' + initials + 'amountvalue';
Tomas Pettersson's avatar
Tomas Pettersson committed
239 240 241 242 243
        amountRowDiv.guideFn = function () {
            self.amountInput.value = '10';
            validate();
        }

Tomas Pettersson's avatar
Tomas Pettersson committed
244
        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
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
        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
283
        self.nextButton.id = 'guide' + initials + 'amount';
Tomas Pettersson's avatar
Tomas Pettersson committed
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
        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
310

Tomas Pettersson's avatar
Tomas Pettersson committed
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
        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
333 334 335
}


Tomas Pettersson's avatar
Tomas Pettersson committed
336 337 338 339
class TrajectoryLineHandler extends LineHandler {

    private _errorShown : any;
    private _mouseDownOrigin : any;
Tomas Pettersson's avatar
Tomas Pettersson committed
340 341 342 343 344 345 346
    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
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
    constructor(time, map, options){
        super(map,options);
    }

    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)) {
Pettersson Tomas's avatar
Pettersson Tomas committed
363 364 365
                // if (this.time.length > 0) {
                    (<any>L).drawLocal.draw.handlers.polyline.tooltip.cont = 'Relase button to stop drawing';                                        
                    // (<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
366 367
                    super.addVertex(latlng);
                    this._mouseDownOrigin = L.point(originalEvent.clientX, originalEvent.clientY);
Pettersson Tomas's avatar
Pettersson Tomas committed
368 369 370 371 372 373 374
                // } else {
                //     super._finishShape();
                //     this._mouseDownOrigin = null;
                //     this._clickHandled = false;
                //     this._disableMarkers = false;                    
                //     return;
                // }
Tomas Pettersson's avatar
Tomas Pettersson committed
375 376 377 378
            }
            //}
        }
    };
Tomas Pettersson's avatar
Tomas Pettersson committed
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
    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
398
    
Tomas Pettersson's avatar
Tomas Pettersson committed
399 400 401
            // Update the mouse marker position
            this._mouseMarker.setLatLng(latlng);
        }
Tomas Pettersson's avatar
Tomas Pettersson committed
402

Tomas Pettersson's avatar
Tomas Pettersson committed
403 404 405
        L.DomEvent.preventDefault(e.originalEvent);
        L.DomEvent.stopPropagation(e.originalEvent);
    };
Tomas Pettersson's avatar
Tomas Pettersson committed
406

Tomas Pettersson's avatar
Tomas Pettersson committed
407
}
Tomas Pettersson's avatar
Tomas Pettersson committed
408

Tomas Pettersson's avatar
Tomas Pettersson committed
409 410 411
class EXTrajectory extends STWkit.AccordionCard {
    public oncallback: Function;
    public lineButton: HTMLButtonElement;
Tomas Pettersson's avatar
Tomas Pettersson committed
412 413
    private lineHandler : any;    
    private trajectoryLayer : L.GeoJSON;
Tomas Pettersson's avatar
Tomas Pettersson committed
414
    private trajectoryLabelLayer : any;
Pettersson Tomas's avatar
Pettersson Tomas committed
415
    private trajMarkerArray : any[];
Tomas Pettersson's avatar
Tomas Pettersson committed
416 417
    public exitControl: L.Control;
    public positions: any[];    
Tomas Pettersson's avatar
Tomas Pettersson committed
418 419
    private map: any;    
    private time: any;    
Pettersson Tomas's avatar
Pettersson Tomas committed
420 421 422
    private from: any;    
    private to: any;    
    private trajlength: number;    
Pettersson Tomas's avatar
Pettersson Tomas committed
423
    private trajpointfeaturecollection: any;    
Pettersson Tomas's avatar
Pettersson Tomas committed
424
    private timeIncrement: number;    // minutes
Tomas Pettersson's avatar
Tomas Pettersson committed
425
    public nextButton: any;
Pettersson Tomas's avatar
Pettersson Tomas committed
426 427 428 429
    endDateInput: HTMLInputElement;
    endTimeInput: HTMLInputElement;
    dateFormat: string;
    timeFormat: string;       
Tomas Pettersson's avatar
Tomas Pettersson committed
430

Pettersson Tomas's avatar
Pettersson Tomas committed
431
    constructor(id, parentDiv, lang, langData, map, domain, type, subtype, initials) {
Tomas Pettersson's avatar
Tomas Pettersson committed
432 433 434
        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
435
        this.map = map;
Tomas Pettersson's avatar
Tomas Pettersson committed
436 437 438 439 440 441 442 443 444 445 446
        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();
        };
Pettersson Tomas's avatar
Pettersson Tomas committed
447 448 449
        self.dateFormat = 'YYYY-MM-DD';
        self.timeFormat = 'HH:mm';

Tomas Pettersson's avatar
Tomas Pettersson committed
450 451 452 453 454 455
        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';
Pettersson Tomas's avatar
Pettersson Tomas committed
456 457 458 459 460 461 462 463 464 465 466
        var fieldset = <HTMLFieldSetElement>L.DomUtil.create('fieldset', 'uk-margin-top', form);        
        var endRowDiv = <HTMLDivElement>L.DomUtil.create('div', 'uk-form-row', fieldset);
        super.addLabelDiv(endRowDiv, "End point date (UTC)", "See more information <a style='color:#faa732;' href='help/classic/?domain=" + domain.toLowerCase() + "#" + type + "-" + subtype + "-start' target='_blank'>here</a>");
        var endDiv = <HTMLDivElement>L.DomUtil.create('div', 'uk-form-controls uk-form-icon uk-width-1-1', endRowDiv);
        var endIcon = <HTMLSpanElement>L.DomUtil.create('span', 'uk-icon-calendar', endDiv);
        self.endDateInput = <HTMLInputElement>L.DomUtil.create('input', 'uk-width-1-2', endDiv);
        self.endDateInput.type = 'text';
        self.endDateInput.placeholder = self.dateFormat;
        self.endTimeInput = <HTMLInputElement>L.DomUtil.create('input', 'uk-width-1-2', endDiv);
        self.endTimeInput.type = 'text';

Tomas Pettersson's avatar
Tomas Pettersson committed
467 468 469 470 471 472
        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';


Pettersson Tomas's avatar
Pettersson Tomas committed
473 474 475 476 477 478 479 480 481 482 483 484 485 486
        self.endDateInput.onchange = function (evt) {

            var date = moment.utc(self.endDateInput.value + ' ' + self.endTimeInput.value, self.datetimeFormat);
            self.to = date.clone();
            self.setTimeIncrement() && self.setTime() && self.updateTrajectoryLabelTimeValues();
        };
        
        self.endTimeInput.onchange = function (evt) {
            var date = moment.utc(self.endDateInput.value + ' ' + self.endTimeInput.value, self.datetimeFormat);
            self.to = date.clone();
            self.setTimeIncrement() && self.setTime() && self.updateTrajectoryLabelTimeValues();
            
        };

Tomas Pettersson's avatar
Tomas Pettersson committed
487 488 489 490 491 492 493 494 495 496 497 498
        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
499
            // self.control.addGeoJSON(geojson);
Tomas Pettersson's avatar
Tomas Pettersson committed
500
        }
Tomas Pettersson's avatar
Tomas Pettersson committed
501

Tomas Pettersson's avatar
Tomas Pettersson committed
502
        var color = '#CA5A1B';
Tomas Pettersson's avatar
Tomas Pettersson committed
503
        this.lineHandler = new TrajectoryLineHandler(null, map, {
Tomas Pettersson's avatar
Tomas Pettersson committed
504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
            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
519
        });
Tomas Pettersson's avatar
Tomas Pettersson committed
520 521
        this.lineHandler.type = 'draw'+id;      
        
Tomas Pettersson's avatar
Tomas Pettersson committed
522 523 524 525


        map.on('zoomend', function () {
            if (self.map.hasLayer(self.trajectoryLabelLayer)) {
Pettersson Tomas's avatar
Pettersson Tomas committed
526
                self.updateTrajectoryLabelVisibility();
Tomas Pettersson's avatar
Tomas Pettersson committed
527 528 529
            }
        });        
        
Tomas Pettersson's avatar
Tomas Pettersson committed
530 531 532 533
        map.on('draw:created', function (e) {
            var type = e.layerType,
                layer = e.layer;
            if (type == 'draw'+id) {
Tomas Pettersson's avatar
Tomas Pettersson committed
534
                var trajlinefeature = layer.toGeoJSON();
Pettersson Tomas's avatar
Pettersson Tomas committed
535 536 537
                if ((trajlinefeature.geometry) && (trajlinefeature.geometry.coordinates.length  > 2)) {
                    self.trajlength = trajlinefeature.geometry.coordinates.length;
                    self.setTimeIncrement() && self.setTime();
Tomas Pettersson's avatar
Tomas Pettersson committed
538
                    self.trajectoryLayer.addData(trajlinefeature);
Pettersson Tomas's avatar
Pettersson Tomas committed
539
                    self.trajpointfeaturecollection = STWkit.featurecollection();
Tomas Pettersson's avatar
Tomas Pettersson committed
540 541 542 543 544 545
                    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;
Pettersson Tomas's avatar
Pettersson Tomas committed
546
                        self.trajpointfeaturecollection.features.push(trajpointfeature);
Tomas Pettersson's avatar
Tomas Pettersson committed
547
                    }
Pettersson Tomas's avatar
Pettersson Tomas committed
548 549 550
                    self.trajectoryLabelLayer.addData(self.trajpointfeaturecollection);    
                                
                    self.updateTrajectoryLabelVisibility();
Tomas Pettersson's avatar
Tomas Pettersson committed
551 552
                    
                }
Tomas Pettersson's avatar
Tomas Pettersson committed
553 554 555 556 557 558 559 560
                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
561 562 563 564 565
                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
566 567

            }
Tomas Pettersson's avatar
Tomas Pettersson committed
568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586
        });             
        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
587
                return marker;
Tomas Pettersson's avatar
Tomas Pettersson committed
588 589
            }
        });
Tomas Pettersson's avatar
Tomas Pettersson committed
590
        
Tomas Pettersson's avatar
Tomas Pettersson committed
591 592
        map.addLayer(this.trajectoryLayer);  
        map.addLayer(this.trajectoryLabelLayer);  
Tomas Pettersson's avatar
Tomas Pettersson committed
593 594

        drawButton.onclick = function () {
Tomas Pettersson's avatar
Tomas Pettersson committed
595
            self.clear();
Tomas Pettersson's avatar
Tomas Pettersson committed
596 597 598 599 600
            var toggleevt = document.createEvent("CustomEvent");
            toggleevt.initCustomEvent('container:toggleVisibility', false, false, {
                'show': false
            });
            window.dispatchEvent(toggleevt);
Tomas Pettersson's avatar
Tomas Pettersson committed
601 602

            self.lineHandler.enable();
Tomas Pettersson's avatar
Tomas Pettersson committed
603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
            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 () {
Pettersson Tomas's avatar
Pettersson Tomas committed
658 659 660
            var endDatePicker = UIkit.datepicker(<any>self.endDateInput, {format: self.dateFormat });
            var endTimePicker = UIkit.timepicker(<any>self.endTimeInput, {});

Tomas Pettersson's avatar
Tomas Pettersson committed
661 662 663 664
            self.defaults();
        });
    }

Tomas Pettersson's avatar
Tomas Pettersson committed
665 666 667
    public changeFn(changeCard) {
        var self = this;
        if ((typeof changeCard.from !== 'undefined') && (typeof changeCard.to !== 'undefined')) {
Pettersson Tomas's avatar
Pettersson Tomas committed
668 669
            self.from = changeCard.from.clone();
            self.to = changeCard.to.clone();
Pettersson Tomas's avatar
Pettersson Tomas committed
670 671 672 673 674
            if (self.endDateInput) {
                self.endDateInput.value =  self.to.format(self.dateFormat);
                self.endTimeInput.value =  self.to.startOf('hour').format(self.timeFormat);
            }
            self.setTimeIncrement() && self.setTime() && self.updateTrajectoryLabelTimeValues();
Pettersson Tomas's avatar
Pettersson Tomas committed
675
       }
Tomas Pettersson's avatar
Tomas Pettersson committed
676 677
    }

Pettersson Tomas's avatar
Pettersson Tomas committed
678 679 680 681 682 683 684 685 686 687
    private setTimeIncrement(){
        this.timeIncrement = -1;
        var len = this.trajlength;
        if (len > 0) {
            var diff = Math.abs(this.from - this.to);
            this.timeIncrement = Math.round(((diff/1000)/60) / len);
            return true;
        }
        return false;
    }
Tomas Pettersson's avatar
Tomas Pettersson committed
688

Pettersson Tomas's avatar
Pettersson Tomas committed
689 690 691 692 693 694 695 696 697 698 699 700 701 702
    public setTime() {
        var self = this;
        self.time = [];
        if (self.timeIncrement > 0 && self.from.isBefore(self.to)) {
            var t = self.from.clone();
            for (var i = 0; i < self.trajlength; i++) {
                self.time.push(t.valueOf());
                t = t.add(self.timeIncrement,'m');
            }
            self.time[self.time.length-1] = self.to.valueOf();
            return true;
        }
        return false;
    }
Tomas Pettersson's avatar
Tomas Pettersson committed
703

Pettersson Tomas's avatar
Pettersson Tomas committed
704 705 706 707 708 709 710 711 712 713 714 715
    private updateTrajectoryLabelTimeValues() {
        var self = this;        
        self.trajMarkerArray = [];        
        self.trajectoryLabelLayer.clearLayers();    
        for (var i = 0; i < self.time.length; i++) 
            self.trajpointfeaturecollection.features[i].properties.time = self.time[i];
        
        self.trajectoryLabelLayer.addData(self.trajpointfeaturecollection);    
        self.updateTrajectoryLabelVisibility();
    }

    private updateTrajectoryLabelVisibility() {
Tomas Pettersson's avatar
Tomas Pettersson committed
716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747
        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
748 749 750 751 752 753 754 755 756
    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
757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773
    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
774 775 776 777 778 779 780 781 782 783 784 785
        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
786 787 788 789 790 791
    }


    public clear() {
        var self = this;
        super.clear();
Tomas Pettersson's avatar
Tomas Pettersson committed
792 793 794
        self.trajectoryLabelLayer.clearLayers();
        self.trajectoryLayer.clearLayers()
        self.trajMarkerArray = [];
Tomas Pettersson's avatar
Tomas Pettersson committed
795
        if (self.lineHandler._enabled) self.lineHandler.disable();
Pettersson Tomas's avatar
Pettersson Tomas committed
796 797 798
        self.timeIncrement = -1;
        self.trajlength = 0;
        self.time = [];
Tomas Pettersson's avatar
Tomas Pettersson committed
799 800 801 802 803 804
        if (self.nextButton) STWkit.AccordionCard.enableNext(self.nextButton, false);
        (self.oncallback && self.oncallback());
    }
}