Subversion Repositories eFlore/Applications.cel

Rev

Rev 3857 | Rev 3869 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
3845 idir 1
import {NOMINATIM_OSM_URL,TbPlaces} from "./modules/Locality.js";
2
 
3
const tileLayers = {
4
    googleHybrid: [
5
        'https://{s}.google.com/vt/lyrs=s,h&x={x}&y={y}&z={z}',
6
        {
7
            attribution: '<a href="https://www.google.com" target="_blank">\xa9 Google Maps</a>',
8
            subdomains: ["mt0","mt1","mt2","mt3"],
9
            maxZoom: 20
10
        }
11
    ],
12
    osm: [
13
        'https://osm.tela-botanica.org/tuiles/osmfr/{z}/{x}/{y}.png',
14
        {
15
            attribution: 'Data © <a href="http://osm.org/copyright">OpenStreetMap</a>',
3864 delphine 16
            maxZoom: 18
3845 idir 17
        }
18
    ]
19
};
20
const defaultPosition = {
21
    lat: 47.0504,
22
    lng: 2.2347
23
};
24
const defaultCityZoom = 12;
25
const defaultZoom = 4;
26
const geometryFilterDefault = 'point';
27
const defaultMapIdAttr = 'tb-geolocation';
28
const markerImgBaseUrl = URL_BASE +'js/tb-geoloc/img/';
29
const markerIcon = L.Icon.extend({
30
    options: {
31
        shadowUrl: markerImgBaseUrl +'marker-shadow.png',
32
        iconAnchor: new L.Point(12, 40),//correctly replaces the dot of the pointer
33
        iconSize: new L.Point(24,40),
34
        iconUrl: markerImgBaseUrl +'marker-icon.png',
35
    }
36
});
37
const defaultPolylineOptions = {
38
    shapeOptions: {
39
        weight: 5
40
    },
41
    showLength: true,
42
    repeatMode: false
43
};
44
 
45
const drawLocale = {
46
    edit: {
47
        handlers: {
48
            edit: {
49
                tooltip: {
50
                    subtext: 'Cliquer sur annuler pour supprimer les changements',
51
                    text: 'Déplacez les marqueurs pour modifier leur position'
52
                }
53
            },
54
            remove: {
55
                tooltip: {
56
                    text: 'cliquer sur une ligne pour supprimer'
57
                }
58
            }
59
        },
60
        toolbar: {
61
            actions: {
62
                cancel: {
63
                    text: 'Annuler',
64
                    title: 'Annuler'
65
                },
66
                clearAll: {
67
                    text: 'Effacer',
68
                    title: 'Tout effacer'
69
                },
70
                save: {
71
                    text: 'Sauvegarder',
72
                    title: 'Sauvegarder les changements'
73
                }
74
            },
75
            buttons: {
76
                edit: 'Editer',
77
                editDisabled: 'Rien à editer',
78
                remove: 'Supprimer',
79
                removeDisabled: 'Rien à supprimer'
80
            }
81
        }
82
    },
83
    draw : {
84
        toolbar: {
85
            actions: {
86
                text: 'Annuler',
87
                title: 'Annuler'
88
            },
89
            buttons: {
90
                polyline: 'Dessiner une ligne',
91
                marker: 'Pointer une position'
92
            },
93
            finish: {
94
                text: 'Terminer',
95
                title: 'Terminer'
96
            },
97
            undo: {
98
                text: 'Supprimer',
99
                title: 'Supprimer le dernier point'
100
            }
101
        },
102
        handlers: {
103
            polyline: {
104
                tooltip: {
105
                    start: 'Cliquer sur la carte pour placer le début de la ligne',
106
                    cont: 'Positionner le prochain point et cliquer',
107
                    end: 'Re-cliquer sur le dernier point pour finir la ligne'
108
                }
109
            },
110
            marker: {
111
                tooltip: {
112
                    start: 'Cliquer sur la carte pour placer le marqueur'
113
                }
114
            },
115
            rectangle: {tooltip: {}},
116
            simpleshape: {tooltip: {}},
117
            circle: {tooltip: {}},
118
            circlemarker: {tooltip: {}}
119
        }
120
    }
121
};
122
 
123
/***************************************************/
124
 
125
export function Geoloc() {
126
    this.map = {};
127
    this.coordinates = defaultPosition;
128
    this.geojson = {};
129
    this.editableLayers = {};
130
    this.defaultDrawControlOptions = {};
131
    this.drawControl = {};
132
    this.defaultEditOptions = false;
133
    this.layer = {};
134
};
135
 
136
Geoloc.prototype.init = function(suffix = '') {
137
    this.mapIdAttr = defaultMapIdAttr + suffix;
138
    this.geolocLabel = document.getElementById('geoloc-label' + suffix);
139
    this.initForm();
140
    this.initEvts();
141
};
142
 
143
Geoloc.prototype.initForm = function() {
144
    this.mapEl = document.getElementById(this.mapIdAttr);
145
    this.zoom = this.mapEl.dataset.zoom || defaultZoom;
146
    this.geometryFilter = this.mapEl.dataset.typeLocalisation || geometryFilterDefault;
147
 
148
    const formSuffix = this.mapEl.dataset.formSuffix;
149
 
150
    this.latitudeEl = document.getElementById('latitude' + formSuffix);
151
    this.longitudeEl = document.getElementById('longitude' + formSuffix);
152
};
153
 
154
Geoloc.prototype.initEvts = function() {
155
    this.initMap();
3864 delphine 156
    this.initMapCoordinates();
3849 idir 157
    this.initSearchLocality();
3845 idir 158
};
159
 
160
Geoloc.prototype.initMap = function() {
161
    this.map = this.createLocationMap();
162
 
163
    // interactions with map
164
    this.map.on(L.Draw.Event.CREATED, evt => {
165
        this.layer = evt.layer;
166
 
167
        // created marker or polyline with drawControl
168
        // no more need this drawcontrol: remove
169
        // (polyline: another one will be added with only edit toolbar)
170
        this.map.removeControl(this.drawControl);
171
 
172
        if ('marker' === evt.layerType) {
173
            this.onMarkerCreated();
174
        } else if ('polyline' === evt.layerType) {
175
            this.handlePolylineEvents();
176
        }
177
    });
178
 
179
    this.map.on(L.Draw.Event.EDITED, evt => {
180
        const layers = evt.layers;
181
 
182
        this.map.removeLayer(this.layer);
183
 
184
        layers.eachLayer(layer => {
185
            this.layer = layer;
186
            this.handlePolylineEvents(false);
187
        });
188
    });
189
 
190
    this.map.on(L.Draw.Event.DELETED, evt => {
191
        this.reSetDrawControl();
192
    });
193
};
194
 
3864 delphine 195
Geoloc.prototype.initMapCoordinates = function() {
196
    if (!!this.latitudeEl.value && !!this.longitudeEl.value) {
197
        this.setMapCoordinates({
198
            'lat': this.latitudeEl.value,
199
            'lng': this.longitudeEl.value
200
        });
201
    }
202
    this.onCoordinates();
203
};
3845 idir 204
 
3864 delphine 205
 
3845 idir 206
Geoloc.prototype.reSetDrawControl = function() {
207
    this.map.removeLayer(this.layer);
208
    this.map.removeControl(this.drawControl);
209
    this.setDrawControl(this.map);
210
};
211
 
212
Geoloc.prototype.createLocationMap = function() {
213
    const lthis = this,
214
        map = L.map(this.mapIdAttr, {zoomControl: true, gestureHandling: true}).setView([this.coordinates.lat, this.coordinates.lng], this.zoom),
215
        tileLayer = this.mapEl.dataset.layer || 'osm';
216
 
217
    L.tileLayer(...tileLayers[tileLayer]).addTo(map);
218
 
219
    this.editableLayers = new L.FeatureGroup();
220
    map.addLayer(this.editableLayers);
221
 
222
    this.setDrawControl(map);
223
 
224
    return map;
225
};
226
 
227
Geoloc.prototype.setDrawControl = function(map) {
228
    this.defaultDrawControlOptions = this.generateDrawControlOptions();
229
    this.drawControl = this.generateDrawControl(...Object.values(this.defaultDrawControlOptions));
230
    map.addControl(this.drawControl);
231
};
232
 
233
Geoloc.prototype.generateDrawControlOptions = function() {
234
    const options = {
235
        editOptions: false,
236
        markerOptions: false,
237
        polylineOptions: false
238
    };
239
 
240
    this.defaultEditOptions = {
241
        featureGroup: this.editableLayers,// REQUIRED!!
242
        remove: true
243
    }
244
 
245
    switch (this.geometryFilter) {
246
        case 'point':
247
            options.markerOptions = {
248
                icon: new markerIcon(),
249
                repeatMode: false
250
            };
251
            break;
252
        case 'rue':
253
            options.polylineOptions = defaultPolylineOptions;
254
            break;
255
        default:
256
            break;
257
    }
258
 
259
    return options;
260
};
261
 
262
Geoloc.prototype.generateDrawControl = function(
263
    editOptions,
264
    markerOptions = false,
265
    polylineOptions = false
266
) {
267
    L.drawLocal = drawLocale;
268
 
269
    return new L.Control.Draw({
270
        position: 'topleft',
271
        draw: {
272
            polyline: polylineOptions,
273
            polygon: false,
274
            circle: false,
275
            rectangle: false,
276
            marker: markerOptions,
277
            circlemarker: false
278
        },
279
        edit: editOptions
280
    });
281
};
282
 
283
Geoloc.prototype.onMarkerCreated = function() {
284
    const coordinates = this.layer.getLatLng();
285
 
286
    this.handleNewLocation(coordinates);
287
};
288
 
289
Geoloc.prototype.handleMarkerEvents = function() {
3847 idir 290
    if(this.map) {
291
        const lthis = this;
292
        // move marker on click
293
        $(this.map).off('click').on('click', function(evt) {
3849 idir 294
            lthis.handleNewLocation(evt.originalEvent.latlng);
3847 idir 295
        });
296
        // move marker on drag
297
        $(this.map.marker).off('dragend').on('dragend', function() {
298
            lthis.handleNewLocation(lthis.map.marker.getLatLng());
299
        });
300
    }
3845 idir 301
};
302
 
303
Geoloc.prototype.handlePolylineEvents = function(requiresNewEditDrawControl = true) {
304
    const latLngs = this.layer.getLatLngs(),
305
        polyline = this.formatPolyline(latLngs),
306
        coordinates = this.layer.getBounds().getCenter();
307
 
308
 
309
    if (requiresNewEditDrawControl) {
310
        this.drawControl = this.generateDrawControl(this.defaultEditOptions);
311
        this.map.addControl(this.drawControl);
312
    }
313
 
314
    // make polyline removable
315
    this.editableLayers.addLayer(L.polyline(latLngs));
316
 
317
    this.map.addLayer(this.layer);
318
    this.handleNewLocation(coordinates, polyline);
319
};
320
 
321
/**
322
 * triggers location event
323
 * @param coordinates.
324
 * @param coordinates.lat latitude.
325
 * @param coordinates.lng longitude.
326
 * @param {array||null} polyline array of coordinates object
327
 */
328
Geoloc.prototype.handleNewLocation = function (coordinates, polyline = []) {
329
    coordinates = this.formatCoordinates(coordinates);
330
 
331
    if(!!coordinates && !!coordinates.lat && coordinates.lng) {
3849 idir 332
        this.zoom = 20;
3848 idir 333
        this.setMapCoordinates(coordinates);
3849 idir 334
 
3848 idir 335
        if('point' === this.geometryFilter) {
336
            this.createDraggableMarker();
337
            this.handleMarkerEvents();
338
        }
3849 idir 339
 
340
        if (
341
            ('rue' === this.geometryFilter && 0 < polyline.length) ||
342
            ('point' === this.geometryFilter && 0 === polyline.length)
343
        ) {
344
            this.getLocationInfo(coordinates, polyline);
345
        }
3845 idir 346
    }
347
};
348
 
349
Geoloc.prototype.formatCoordinates = function (coordinates) {
350
    coordinates.lat = Number.parseFloat(coordinates.lat);
351
    coordinates.lng = Number.parseFloat(coordinates.lng);
352
 
353
    if(Number.isNaN(coordinates.lat) || Number.isNaN(coordinates.lng)) {
354
        return null;
355
    }
356
 
357
    return coordinates;
358
};
359
 
360
Geoloc.prototype.formatPolyline = function (latLngs) {
361
    const polyline = [];
362
 
363
    latLngs.forEach(coordinates => polyline.push(Object.values(coordinates)));
364
 
365
    return polyline;
366
};
367
 
3848 idir 368
Geoloc.prototype.setMapCoordinates = function (coordinates) {
3845 idir 369
    this.coordinates = coordinates;
370
    // updates map
3849 idir 371
    this.map.setView(coordinates,this.zoom);
3845 idir 372
};
373
 
3848 idir 374
Geoloc.prototype.createDraggableMarker = function() {
3845 idir 375
    if (undefined === this.map.marker) {
376
        // after many attempts, did not manage
377
        // to make marker from draw control draggable
378
        // solution: replace it
379
        if(this.layer) {
380
            this.map.removeLayer(this.layer);
381
        }
382
        this.map.marker = new L.Marker(this.coordinates, {
383
            draggable: true,
384
            icon: new markerIcon()
385
        });
386
        this.layer = this.map.marker;
387
        this.map.addLayer(this.map.marker);
388
        if(this.drawControl) {
389
            this.map.removeControl(this.drawControl);
390
        }
391
    }
392
 
3848 idir 393
    this.map.marker.setLatLng(this.coordinates, {draggable: 'true'});
3845 idir 394
};
395
 
396
Geoloc.prototype.getLocationInfo = function(coordinates, polyline) {
397
    const lthis = this,
398
        url = NOMINATIM_OSM_URL+'reverse',
399
        params = {
400
            'format': 'json',
401
            'lat': coordinates.lat,
402
            'lon': coordinates.lng
403
        };
404
 
405
    this.geolocLabel.classList.add('loading');
406
 
407
    $.ajax({
408
        method: "GET",
409
        url: url,
410
        data: params,
411
        success: function(locationData) {
412
            lthis.loadGeolocation(coordinates,locationData,polyline);
413
        },
414
        error: (err) => {
415
            console.warn(err);
416
            lthis.geolocLabel.classList.remove('loading');
417
        }
418
    });
419
};
420
 
421
Geoloc.prototype.loadGeolocation = function(coordinates,locationData,polyline) {
422
    const lthis = this,
423
        query = {
424
            'lat': coordinates.lat,
425
            'lon': coordinates.lng
426
        };
427
 
428
    $.ajax({
429
        method: "GET",
430
        url: URL_GEOLOC_SERVICE,
431
        data: query,
432
        success: function (geoLocationData) {
433
            lthis.triggerLocationEvent(
434
                lthis.formatLocationEventObject(coordinates,geoLocationData,locationData,polyline)
435
            );
436
            lthis.geolocLabel.classList.remove('loading');
437
        },
438
        error:  (err) => {
439
            console.warn(err);
440
            lthis.geolocLabel.classList.remove('loading');
441
        }
442
    });
443
};
444
 
445
Geoloc.prototype.triggerLocationEvent = function (locationDataObject) {
446
    const location = new CustomEvent('location', {detail: locationDataObject});
447
 
448
    this.mapEl.dispatchEvent(location);
449
};
450
 
451
Geoloc.prototype.formatLocationEventObject = function(coordinates,geoLocationData,locationData,polyline) {
452
    const detail = {
453
        centroid: {
454
            type: 'Point',
455
            coordinates: Object.values(coordinates)
456
        },
457
        elevation: geoLocationData.altitude,
458
        inseeData: {
459
            code: geoLocationData.code_zone,
460
            nom: geoLocationData.nom
461
        },
462
        osmCountry: locationData.address.country,
463
        osmCountryCode: geoLocationData.code_pays,
464
        osmCounty: locationData.address.county,
465
        osmPostcode:locationData.address.postcode,
466
        locality: this.getLocalityFromData(locationData),
467
        locality: geoLocationData.nom,
468
        osmRoad: locationData.address.road,
469
        osmState: locationData.address.state,
470
        osmId: locationData.osm_id,
471
        osmPlaceId: locationData.place_id
472
    };
473
 
474
    if (0 < polyline.length) {
475
        detail.geometry = {
476
            type: 'LineString',
477
            coordinates: polyline
478
        };
479
    } else {
480
        detail.geometry = detail.centroid;
481
    }
482
 
483
    return detail;
484
}
485
 
486
Geoloc.prototype.handleCoordinates = function() {
487
    if (!!this.latitudeEl.value && !!this.longitudeEl.value) {
488
        this.handleNewLocation({
489
            'lat': this.latitudeEl.value,
490
            'lng': this.longitudeEl.value
491
        });
492
    }
493
};
494
 
495
Geoloc.prototype.onCoordinates = function() {
496
    [this.latitudeEl,this.longitudeEl].forEach(coordinate =>
497
        coordinate.addEventListener('blur', function() {
498
            this.handleCoordinates();
499
        }.bind(this))
500
    );
501
};
502
 
503
Geoloc.prototype.initSearchLocality = function() {
504
    const placesZone = document.getElementById('tb-places-zone');
505
 
506
    if(placesZone) {
507
        placesZone.classList.remove('hidden');
508
        this.tbPlaces = new TbPlaces(this.tbPlacesCallback.bind(this));
509
        this.tbPlaces.init();
510
    }
511
};
512
 
513
Geoloc.prototype.tbPlacesCallback = function(localityData) {
514
    const locality = this.getLocalityFromData(localityData);
515
 
516
    if(!!locality) {
517
        const coordinates = {
518
            'lat' : localityData.lat,
519
            'lng' : localityData.lon
520
        };
521
 
3849 idir 522
        if ('point' === this.geometryFilter) {
523
            this.map.removeControl(this.drawControl);
524
        }
525
        this.zoom = 18;
3845 idir 526
        this.handleNewLocation(coordinates);
527
    }
528
};
529
 
530
Geoloc.prototype.getLocalityFromData = function(localityData) {
531
    const addressData = localityData.address,
532
        locationNameType = ['village', 'city', 'locality', 'municipality', 'county'].find(locationNameType => addressData[locationNameType] !== undefined);
533
 
534
    if (!locationNameType) {
535
        return;
536
    }
537
 
538
    return addressData[locationNameType];
539
};
540
 
541
Geoloc.prototype.closeMap = function () {
542
    // reset map
543
    this.map = L.DomUtil.get(this.mapIdAttr);
544
    if (this.map != null) {
545
        this.map._leaflet_id = null;
546
    }
547
};