Subversion Repositories eFlore/Applications.cel

Rev

Rev 3871 | Only display areas with differences | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

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