Subversion Repositories eFlore/Applications.cel

Rev

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