Subversion Repositories eFlore/Applications.cel

Rev

Rev 3857 | Rev 3869 | Go to most recent revision | Only display areas with differences | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

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