Subversion Repositories eFlore/Applications.cel

Rev

Rev 3870 | 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: [
3954 delphine 13
        'https://b.tile.openstreetmap.fr/osmfr/{z}/{x}/{y}.png',
3845 idir 14
        {
15
            attribution: 'Data © <a href="http://osm.org/copyright">OpenStreetMap</a>',
3862 idir 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();
3862 idir 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
 
3862 idir 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
 
205
Geoloc.prototype.reSetDrawControl = function() {
206
    this.map.removeLayer(this.layer);
207
    this.map.removeControl(this.drawControl);
208
    this.setDrawControl(this.map);
209
};
210
 
211
Geoloc.prototype.createLocationMap = function() {
212
    const lthis = this,
213
        map = L.map(this.mapIdAttr, {zoomControl: true, gestureHandling: true}).setView([this.coordinates.lat, this.coordinates.lng], this.zoom),
214
        tileLayer = this.mapEl.dataset.layer || 'osm';
215
 
216
    L.tileLayer(...tileLayers[tileLayer]).addTo(map);
217
 
218
    this.editableLayers = new L.FeatureGroup();
219
    map.addLayer(this.editableLayers);
220
 
221
    this.setDrawControl(map);
222
 
223
    return map;
224
};
225
 
226
Geoloc.prototype.setDrawControl = function(map) {
227
    this.defaultDrawControlOptions = this.generateDrawControlOptions();
228
    this.drawControl = this.generateDrawControl(...Object.values(this.defaultDrawControlOptions));
229
    map.addControl(this.drawControl);
230
};
231
 
232
Geoloc.prototype.generateDrawControlOptions = function() {
233
    const options = {
234
        editOptions: false,
235
        markerOptions: false,
236
        polylineOptions: false
237
    };
238
 
239
    this.defaultEditOptions = {
240
        featureGroup: this.editableLayers,// REQUIRED!!
241
        remove: true
242
    }
243
 
244
    switch (this.geometryFilter) {
245
        case 'point':
246
            options.markerOptions = {
247
                icon: new markerIcon(),
248
                repeatMode: false
249
            };
250
            break;
251
        case 'rue':
252
            options.polylineOptions = defaultPolylineOptions;
253
            break;
254
        default:
255
            break;
256
    }
257
 
258
    return options;
259
};
260
 
261
Geoloc.prototype.generateDrawControl = function(
262
    editOptions,
263
    markerOptions = false,
264
    polylineOptions = false
265
) {
266
    L.drawLocal = drawLocale;
267
 
268
    return new L.Control.Draw({
269
        position: 'topleft',
270
        draw: {
271
            polyline: polylineOptions,
272
            polygon: false,
273
            circle: false,
274
            rectangle: false,
275
            marker: markerOptions,
276
            circlemarker: false
277
        },
278
        edit: editOptions
279
    });
280
};
281
 
282
Geoloc.prototype.onMarkerCreated = function() {
283
    const coordinates = this.layer.getLatLng();
284
 
285
    this.handleNewLocation(coordinates);
286
};
287
 
288
Geoloc.prototype.handleMarkerEvents = function() {
3847 idir 289
    if(this.map) {
290
        const lthis = this;
291
        // move marker on click
292
        $(this.map).off('click').on('click', function(evt) {
3849 idir 293
            lthis.handleNewLocation(evt.originalEvent.latlng);
3847 idir 294
        });
295
        // move marker on drag
296
        $(this.map.marker).off('dragend').on('dragend', function() {
297
            lthis.handleNewLocation(lthis.map.marker.getLatLng());
298
        });
299
    }
3845 idir 300
};
301
 
302
Geoloc.prototype.handlePolylineEvents = function(requiresNewEditDrawControl = true) {
303
    const latLngs = this.layer.getLatLngs(),
304
        polyline = this.formatPolyline(latLngs),
305
        coordinates = this.layer.getBounds().getCenter();
306
 
307
 
308
    if (requiresNewEditDrawControl) {
309
        this.drawControl = this.generateDrawControl(this.defaultEditOptions);
310
        this.map.addControl(this.drawControl);
311
    }
312
 
313
    // make polyline removable
314
    this.editableLayers.addLayer(L.polyline(latLngs));
315
 
316
    this.map.addLayer(this.layer);
317
    this.handleNewLocation(coordinates, polyline);
318
};
319
 
320
/**
321
 * triggers location event
322
 * @param coordinates.
323
 * @param coordinates.lat latitude.
324
 * @param coordinates.lng longitude.
325
 * @param {array||null} polyline array of coordinates object
326
 */
327
Geoloc.prototype.handleNewLocation = function (coordinates, polyline = []) {
328
    coordinates = this.formatCoordinates(coordinates);
329
 
330
    if(!!coordinates && !!coordinates.lat && coordinates.lng) {
3849 idir 331
        this.zoom = 20;
3848 idir 332
        this.setMapCoordinates(coordinates);
3849 idir 333
 
3848 idir 334
        if('point' === this.geometryFilter) {
335
            this.createDraggableMarker();
336
            this.handleMarkerEvents();
337
        }
3849 idir 338
 
339
        if (
340
            ('rue' === this.geometryFilter && 0 < polyline.length) ||
341
            ('point' === this.geometryFilter && 0 === polyline.length)
342
        ) {
343
            this.getLocationInfo(coordinates, polyline);
344
        }
3845 idir 345
    }
346
};
347
 
348
Geoloc.prototype.formatCoordinates = function (coordinates) {
349
    coordinates.lat = Number.parseFloat(coordinates.lat);
350
    coordinates.lng = Number.parseFloat(coordinates.lng);
351
 
352
    if(Number.isNaN(coordinates.lat) || Number.isNaN(coordinates.lng)) {
353
        return null;
354
    }
355
 
356
    return coordinates;
357
};
358
 
359
Geoloc.prototype.formatPolyline = function (latLngs) {
360
    const polyline = [];
361
 
3867 idir 362
    latLngs.forEach(coordinates => polyline.push(Object.values(coordinates).reverse()));
3845 idir 363
 
364
    return polyline;
365
};
366
 
3848 idir 367
Geoloc.prototype.setMapCoordinates = function (coordinates) {
3845 idir 368
    this.coordinates = coordinates;
369
    // updates map
3849 idir 370
    this.map.setView(coordinates,this.zoom);
3845 idir 371
};
372
 
3848 idir 373
Geoloc.prototype.createDraggableMarker = function() {
3845 idir 374
    if (undefined === this.map.marker) {
375
        // after many attempts, did not manage
376
        // to make marker from draw control draggable
377
        // solution: replace it
378
        if(this.layer) {
379
            this.map.removeLayer(this.layer);
380
        }
381
        this.map.marker = new L.Marker(this.coordinates, {
382
            draggable: true,
383
            icon: new markerIcon()
384
        });
385
        this.layer = this.map.marker;
386
        this.map.addLayer(this.map.marker);
387
        if(this.drawControl) {
388
            this.map.removeControl(this.drawControl);
389
        }
390
    }
391
 
3848 idir 392
    this.map.marker.setLatLng(this.coordinates, {draggable: 'true'});
3845 idir 393
};
394
 
395
Geoloc.prototype.getLocationInfo = function(coordinates, polyline) {
396
    const lthis = this,
397
        url = NOMINATIM_OSM_URL+'reverse',
398
        params = {
399
            'format': 'json',
400
            'lat': coordinates.lat,
401
            'lon': coordinates.lng
402
        };
403
 
404
    this.geolocLabel.classList.add('loading');
405
 
406
    $.ajax({
407
        method: "GET",
408
        url: url,
409
        data: params,
410
        success: function(locationData) {
3866 idir 411
            locationData.centroid = lthis.formatPointTypeCoordinates(coordinates);
412
            locationData.geojson = 'rue' === lthis.geometryFilter ? {type: 'LineString', coordinates: polyline} : locationData.centroid;
413
            lthis.loadGeolocation(coordinates,locationData);
3845 idir 414
        },
415
        error: (err) => {
416
            console.warn(err);
417
            lthis.geolocLabel.classList.remove('loading');
418
        }
419
    });
420
};
421
 
3866 idir 422
Geoloc.prototype.formatPointTypeCoordinates = function(coordinates) {
3867 idir 423
    return {type : 'Point', coordinates: Object.values(coordinates).reverse()};
3866 idir 424
};
425
 
426
Geoloc.prototype.loadGeolocation = function(coordinates,locationData) {
3845 idir 427
    const lthis = this,
428
        query = {
429
            'lat': coordinates.lat,
430
            'lon': coordinates.lng
431
        };
432
 
433
    $.ajax({
434
        method: "GET",
435
        url: URL_GEOLOC_SERVICE,
436
        data: query,
437
        success: function (geoLocationData) {
438
            lthis.triggerLocationEvent(
3866 idir 439
                lthis.formatLocationEventObject(locationData,geoLocationData)
3845 idir 440
            );
441
            lthis.geolocLabel.classList.remove('loading');
442
        },
443
        error:  (err) => {
444
            console.warn(err);
445
            lthis.geolocLabel.classList.remove('loading');
446
        }
447
    });
448
};
449
 
3866 idir 450
Geoloc.prototype.triggerLocationEvent = function(locationDataObject) {
451
    const locationEvent = new CustomEvent('location', {detail: locationDataObject});
3845 idir 452
 
3866 idir 453
    this.mapEl.dispatchEvent(locationEvent);
3845 idir 454
};
455
 
3866 idir 456
Geoloc.prototype.formatLocationEventObject = function(locationData,geoLocationData) {
3845 idir 457
    const detail = {
3866 idir 458
        centroid: locationData.centroid,
459
        geometry: locationData.geojson,
3845 idir 460
        elevation: geoLocationData.altitude,
461
        inseeData: {
3870 idir 462
            code: 'FR' === geoLocationData.code_pays ? geoLocationData.code_zone : '',
3845 idir 463
            nom: geoLocationData.nom
464
        },
465
        osmCountry: locationData.address.country,
466
        osmCountryCode: geoLocationData.code_pays,
467
        osmCounty: locationData.address.county,
3866 idir 468
        osmPostcode: locationData.address.postcode,
3845 idir 469
        locality: this.getLocalityFromData(locationData),
470
        locality: geoLocationData.nom,
471
        osmRoad: locationData.address.road,
472
        osmState: locationData.address.state,
473
        osmId: locationData.osm_id,
474
        osmPlaceId: locationData.place_id
475
    };
476
 
477
    return detail;
3866 idir 478
};
3845 idir 479
 
480
Geoloc.prototype.handleCoordinates = function() {
481
    if (!!this.latitudeEl.value && !!this.longitudeEl.value) {
482
        this.handleNewLocation({
483
            'lat': this.latitudeEl.value,
484
            'lng': this.longitudeEl.value
485
        });
486
    }
487
};
488
 
489
Geoloc.prototype.onCoordinates = function() {
490
    [this.latitudeEl,this.longitudeEl].forEach(coordinate =>
491
        coordinate.addEventListener('blur', function() {
492
            this.handleCoordinates();
493
        }.bind(this))
494
    );
495
};
496
 
497
Geoloc.prototype.initSearchLocality = function() {
498
    const placesZone = document.getElementById('tb-places-zone');
499
 
500
    if(placesZone) {
501
        placesZone.classList.remove('hidden');
502
        this.tbPlaces = new TbPlaces(this.tbPlacesCallback.bind(this));
503
        this.tbPlaces.init();
504
    }
505
};
506
 
507
Geoloc.prototype.tbPlacesCallback = function(localityData) {
508
    const locality = this.getLocalityFromData(localityData);
509
 
510
    if(!!locality) {
3866 idir 511
        const coordinates = this.formatCoordinates({
3845 idir 512
            'lat' : localityData.lat,
513
            'lng' : localityData.lon
3866 idir 514
        });
3845 idir 515
 
3866 idir 516
        if(!!coordinates && !!coordinates.lat && !!coordinates.lng) {
517
            this.zoom = 20;
518
            this.setMapCoordinates(coordinates);
519
 
520
            if('point' === this.geometryFilter) {
521
                this.map.removeControl(this.drawControl);
522
                this.createDraggableMarker();
523
                this.handleMarkerEvents();
524
            }
525
 
526
            localityData.centroid = this.formatPointTypeCoordinates(coordinates);
527
            if('rue' !== this.geometryFilter && 'Polygon' === localityData.geojson.type ) {
528
                localityData.geojson = localityData.centroid;
529
            }
530
            this.loadGeolocation(coordinates,localityData);
3849 idir 531
        }
3845 idir 532
    }
533
};
534
 
535
Geoloc.prototype.getLocalityFromData = function(localityData) {
536
    const addressData = localityData.address,
537
 
3870 idir 538
        locationNameType = ['village', 'city', 'locality', 'municipality', 'county', 'state'].find(locationNameType => addressData[locationNameType] !== undefined);
3845 idir 539
    if (!locationNameType) {
540
        return;
541
    }
542
 
543
    return addressData[locationNameType];
544
};
545
 
546
Geoloc.prototype.closeMap = function () {
547
    // reset map
548
    this.map = L.DomUtil.get(this.mapIdAttr);
549
    if (this.map != null) {
550
        this.map._leaflet_id = null;
551
    }
3862 idir 552
};