From 04a1d01904442d1441862914171df5436950e059 Mon Sep 17 00:00:00 2001 From: Alix JEUDI--LEMOINE Date: Wed, 28 May 2025 19:49:14 +0200 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20Now=20complete=20address=20is=20sen?= =?UTF-8?q?t=20to=20API=20to=20avoid=20multiple=20nominatim=20requests?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../add-pin-popup/add-pin-popup.component.ts | 26 +++---- .../edit-pin-popup.component.ts | 71 ++++++------------- .../leaflet-map/leaflet-map.component.ts | 29 ++------ src/app/model/Pin.ts | 1 + src/app/services/pin/pin.service.ts | 51 ++----------- 5 files changed, 48 insertions(+), 130 deletions(-) diff --git a/src/app/components/add-pin-popup/add-pin-popup.component.ts b/src/app/components/add-pin-popup/add-pin-popup.component.ts index 4c47738..2355af1 100644 --- a/src/app/components/add-pin-popup/add-pin-popup.component.ts +++ b/src/app/components/add-pin-popup/add-pin-popup.component.ts @@ -50,6 +50,8 @@ export class AddPinPopupComponent implements OnInit { title: new FormControl(''), description: new FormControl(''), location: new FormControl(''), + complete_address: new FormControl(''), + coordinates: new FormControl([]), files: new FormControl(null), date: new FormControl(''), }); @@ -106,6 +108,8 @@ export class AddPinPopupComponent implements OnInit { const locationControl = this.form.get('location'); if (locationControl instanceof FormControl) { locationControl.setValue(suggestion.display_name); + this.form.get('complete_address')?.setValue(suggestion.display_name); + this.form.get('coordinates')?.setValue([suggestion.lat, suggestion.lon]); } this.suggestions = []; } @@ -123,6 +127,8 @@ export class AddPinPopupComponent implements OnInit { if (address) { console.error('Data : ' + JSON.stringify(address)); this.form.get('location')?.setValue(address.display_name); + this.form.get('complete_address')?.setValue(address.display_name); + this.form.get('coordinates')?.setValue([data.latitude, data.longitude]); break; } } @@ -137,32 +143,26 @@ export class AddPinPopupComponent implements OnInit { } submitForm(): void { - // if (this.form.valid) { - // this.files = this.files.map((file) => { - // // return file.name; //TODO: Mettre le hash du fichier - // this.imageService.postImage(file).subscribe((response) => { - // // console.log('Image uploaded:', response); - // let imageId = response.json(); - // return imageId.id; - // }); - // }); - // console.log('Files : ' + JSON.stringify(this.files)); - if (this.form.valid) { const uploadObservables = this.files.map((file) => this.imageService.postImage(file) ); forkJoin(uploadObservables).subscribe((responses) => { - // responses est un tableau de réponses API - this.files = responses.map((res: any) => res.id); // ou res.json().id si nécessaire + this.files = responses.map((res: any) => res.id); + const coordinates = this.form.get('coordinates')?.value; const pinData = { ...this.form.value, files: this.files, date: this.form.get('date')?.value || null, + location: coordinates || [0, 0], // Utiliser les coordonnées pour location + complete_address: this.form.get('complete_address')?.value || this.form.get('location')?.value, }; + // Supprimer le champ coordinates qui n'est pas dans le modèle Pin + delete pinData.coordinates; + console.log('Files : ' + JSON.stringify(this.files)); console.log('Pin Data : ' + JSON.stringify(pinData)); diff --git a/src/app/components/edit-pin-popup/edit-pin-popup.component.ts b/src/app/components/edit-pin-popup/edit-pin-popup.component.ts index f56b6d7..8df3d77 100644 --- a/src/app/components/edit-pin-popup/edit-pin-popup.component.ts +++ b/src/app/components/edit-pin-popup/edit-pin-popup.component.ts @@ -65,6 +65,8 @@ export class EditPinPopupComponent implements OnInit, AfterViewInit, OnDestroy { title: new FormControl(''), description: new FormControl(''), location: new FormControl(''), + complete_address: new FormControl(''), + coordinates: new FormControl([]), files: new FormControl(null), date: new FormControl(''), }); @@ -85,43 +87,12 @@ export class EditPinPopupComponent implements OnInit, AfterViewInit, OnDestroy { this.form.patchValue({ title: this.pin?.title || '', description: this.pin?.description || '', - location: "Chargement de l'adresse...", + location: this.pin?.complete_address || '', + complete_address: this.pin?.complete_address || '', + coordinates: this.pin?.location || [], date: this.pin?.date || '', }); - // Vérifier si nous avons des coordonnées valides dans pin.location - if ( - this.pin?.location && - Array.isArray(this.pin.location) && - this.pin.location.length >= 2 - ) { - const lat = this.pin.location[0]; - const lon = this.pin.location[1]; - - if (lat !== undefined && lon !== undefined) { - // Récupérer l'adresse à partir des coordonnées - this.locationSubscription = this.autocompleteService - .getAddressFromCoordinates(lat, lon) - .pipe(take(1)) - .subscribe( - (address) => { - if (address && address.display_name) { - this.form.patchValue({ location: address.display_name }); - } else { - this.form.patchValue({ location: `${lat}, ${lon}` }); - } - }, - (error) => { - console.error( - "Erreur lors de la récupération de l'adresse:", - error - ); - this.form.patchValue({ location: `${lat}, ${lon}` }); - } - ); - } - } - // S'abonner aux changements d'état du modal this.modalOpenSubscription = this.modalService .getModalState(this.modalId) @@ -147,7 +118,7 @@ export class EditPinPopupComponent implements OnInit, AfterViewInit, OnDestroy { debounceTime(300), // Attendre 300ms après la dernière frappe distinctUntilChanged(), // Ignorer si la nouvelle valeur est la même que la précédente switchMap((query) => { - // Vérifier que query est une chaîne de caractères + // Vérifier que query est une chaîne de caractères if (typeof query !== 'string') { return of([]); } @@ -204,6 +175,8 @@ export class EditPinPopupComponent implements OnInit, AfterViewInit, OnDestroy { const locationControl = this.form.get('location'); if (locationControl instanceof FormControl) { locationControl.setValue(suggestion.display_name); + this.form.get('complete_address')?.setValue(suggestion.display_name); + this.form.get('coordinates')?.setValue([suggestion.lat, suggestion.lon]); } this.suggestions = []; } @@ -224,17 +197,16 @@ export class EditPinPopupComponent implements OnInit, AfterViewInit, OnDestroy { if (address) { this.form.get('location')?.setValue(address.display_name); + this.form.get('complete_address')?.setValue(address.display_name); + this.form.get('coordinates')?.setValue([data.latitude, data.longitude]); break; } } catch (addressError) { - console.error( - "Erreur lors de la récupération de l'adresse:", - addressError - ); + console.error("Erreur lors de la récupération de l'adresse:", addressError); // Utiliser les coordonnées brutes en cas d'échec - this.form - .get('location') - ?.setValue(`${data.latitude}, ${data.longitude}`); + this.form.get('location')?.setValue(`${data.latitude}, ${data.longitude}`); + this.form.get('complete_address')?.setValue(`${data.latitude}, ${data.longitude}`); + this.form.get('coordinates')?.setValue([data.latitude, data.longitude]); } } } catch (error) { @@ -245,23 +217,22 @@ export class EditPinPopupComponent implements OnInit, AfterViewInit, OnDestroy { submitForm(): void { if (this.form.valid) { - this.files = this.files.map((file) => { - return file.name; //TODO: Mettre le hash du fichier - }); - + const coordinates = this.form.get('coordinates')?.value; const pinData = { ...this.form.value, files: this.files, - user_id: this.pin.user_id, date: this.form.get('date')?.value || null, + location: coordinates || this.pin.location, // Utiliser les coordonnées pour location + complete_address: this.form.get('complete_address')?.value || this.form.get('location')?.value, }; + // Supprimer le champ coordinates qui n'est pas dans le modèle Pin + delete pinData.coordinates; + this.pinService.updatePin(this.pin.id, pinData).subscribe(() => { - this.mapReloadService.requestReload(); // Demander le rechargement de la carte + this.mapReloadService.requestReload(); this.closePinModal(); }); - } else { - console.error('Le formulaire est invalide'); } } diff --git a/src/app/components/leaflet-map/leaflet-map.component.ts b/src/app/components/leaflet-map/leaflet-map.component.ts index 342b408..adaa7e6 100644 --- a/src/app/components/leaflet-map/leaflet-map.component.ts +++ b/src/app/components/leaflet-map/leaflet-map.component.ts @@ -91,28 +91,13 @@ export class LeafletMapComponent implements OnInit { private loadCountriesForFiltrers(pins: Pin[]): void { const countrySet = new Set(); - const requests = pins.map((pin) => - this.autocompleteService - .getAddressFromCoordinates(pin.location[0], pin.location[1]) - .toPromise() - .then((res: any) => { - const address = res?.address; - const country = - address?.country || - this.extractLastFromDisplayName(res?.display_name); - if (country) { - this.pinCountries[pin.id] = country; - countrySet.add(country); - } - }) - .catch((err: any) => { - console.error( - 'Erreur lors de la récupération du pays pour le pin', - pin.id, - err - ); - }) - ); + const requests = pins.map((pin: Pin) => { + const country = this.extractLastFromDisplayName(pin.complete_address); + if (country) { + this.pinCountries[pin.id] = country; + countrySet.add(country); + } + }); Promise.all(requests).then(() => { this.availableCountries = Array.from(countrySet).sort(); diff --git a/src/app/model/Pin.ts b/src/app/model/Pin.ts index 0e04110..579e9bd 100644 --- a/src/app/model/Pin.ts +++ b/src/app/model/Pin.ts @@ -1,6 +1,7 @@ export interface Pin { id: string; location: number[]; + complete_address: string; title: string; files: string[]; description: string; diff --git a/src/app/services/pin/pin.service.ts b/src/app/services/pin/pin.service.ts index 4d11d82..d791c14 100644 --- a/src/app/services/pin/pin.service.ts +++ b/src/app/services/pin/pin.service.ts @@ -29,46 +29,20 @@ export class PinService { return this.http.get(url, { headers }); } - addPin(pin: { - title: string; - description: string; - location: string; - files: string[]; - date: string; - }) { + addPin(pin: Pin) { const url = `${this.apiURL}/pin/add`; const headers = new HttpHeaders({ 'Content-Type': 'application/json', Authorization: 'Bearer ' + localStorage.getItem('auth_token'), }); - return this.autoCompleteService.getAdressCoordinates(pin.location).pipe( - switchMap((response: any) => { - const coords: [string, string] = [response[0].lat, response[0].lon]; - return this.http.post( - url, - { - title: pin.title, - description: pin.description, - location: coords, - files: pin.files, - user_id: '', - date: pin.date, - }, - { headers } - ); - }) + return this.http.post( + url, pin, { headers } ); } updatePin( id: string, - pin: { - title: string; - description: string; - location: string; - files: any[]; - user_id: string; - } + pin: Pin ) { const url = `${this.apiURL}/pin/${id}`; const headers = new HttpHeaders({ @@ -77,21 +51,8 @@ export class PinService { }); // Obtenir les coordonnées GPS à partir de l'adresse - return this.autoCompleteService.getAdressCoordinates(pin.location).pipe( - switchMap((response: any) => { - const coords: [string, string] = [response[0].lat, response[0].lon]; - return this.http.patch( - url, - { - title: pin.title, - description: pin.description, - location: coords, - files: pin.files, - user_id: pin.user_id, - }, - { headers } - ); - }) + return this.http.patch( + url, pin, { headers } ); }