From acb0db6f76e0a342f86bbb5ac82bca92020c2c57 Mon Sep 17 00:00:00 2001
From: Hugo SUBTIL <ext.sopra.husubtil@grandlyon.com>
Date: Fri, 23 Oct 2020 18:03:57 +0200
Subject: [PATCH] feat: add distance calculation for cards

---
 proxy.conf.json                               |  6 ++
 src/app/home/home.component.html              |  2 +-
 src/app/home/home.component.ts                | 30 +++++-
 src/app/map/components/map.component.ts       |  8 +-
 src/app/map/services/geojson.service.ts       | 33 -------
 src/app/{map => }/models/address.model.ts     |  0
 .../services/geojson.service.spec.ts          |  2 +-
 src/app/services/geojson.service.ts           | 99 +++++++++++++++++++
 .../components/card/card.component.html       |  2 +-
 .../components/card/card.component.ts         | 50 +++++++++-
 .../recherche/recherche.component.ts          |  2 +-
 .../structure-list.component.html             |  2 +-
 .../structure-list.component.ts               |  3 +-
 13 files changed, 190 insertions(+), 49 deletions(-)
 delete mode 100644 src/app/map/services/geojson.service.ts
 rename src/app/{map => }/models/address.model.ts (100%)
 rename src/app/{map => }/services/geojson.service.spec.ts (96%)
 create mode 100644 src/app/services/geojson.service.ts

diff --git a/proxy.conf.json b/proxy.conf.json
index 4cafc6d48..f6d20c2ac 100644
--- a/proxy.conf.json
+++ b/proxy.conf.json
@@ -13,5 +13,11 @@
     "secure": false,
     "changeOrigin": true,
     "logLevel": "info"
+  },
+  "/reverse": {
+    "target": "https://api-adresse.data.gouv.fr",
+    "secure": false,
+    "changeOrigin": true,
+    "logLevel": "info"
   }
 }
diff --git a/src/app/home/home.component.html b/src/app/home/home.component.html
index 6016ec21f..163c415cb 100644
--- a/src/app/home/home.component.html
+++ b/src/app/home/home.component.html
@@ -1,4 +1,4 @@
 <div fxLayout="row">
-  <app-structure-list [structureList]="structures" class="left-pane"></app-structure-list>
+  <app-structure-list [structureList]="structures" [location]="currentLocation" class="left-pane"></app-structure-list>
   <app-map [structures]="structures" fxFlex="100"></app-map>
 </div>
diff --git a/src/app/home/home.component.ts b/src/app/home/home.component.ts
index 2264953e0..ddf4ebc84 100644
--- a/src/app/home/home.component.ts
+++ b/src/app/home/home.component.ts
@@ -1,7 +1,8 @@
 import { Component, OnInit } from '@angular/core';
-import { mergeMap } from 'rxjs/operators';
 import { Structure } from '../models/structure.model';
 import { StructureService } from '../services/structure-list.service';
+import { GeoJson } from '../map/models/geojson.model';
+import { GeojsonService } from '../services/geojson.service';
 const { DateTime } = require('luxon');
 
 @Component({
@@ -11,13 +12,38 @@ const { DateTime } = require('luxon');
 })
 export class HomeComponent implements OnInit {
   public structures: Structure[] = [];
-  constructor(private structureService: StructureService) {}
+  public geolocation = false;
+  public currentLocation: GeoJson;
+  constructor(private structureService: StructureService, private geojsonService: GeojsonService) {}
 
   ngOnInit(): void {
+    this.getStructures();
+    if (navigator.geolocation) {
+      this.getLocation();
+    }
+  }
+
+  public getStructures(): void {
     this.structureService.getStructures().subscribe((structures) => {
       this.structures = structures.map((structure) =>
         this.structureService.updateOpeningStructure(structure, DateTime.local())
       );
     });
   }
+
+  public getLocation(): void {
+    navigator.geolocation.getCurrentPosition((position) => {
+      this.geolocation = true;
+      const longitude = position.coords.longitude;
+      const latitude = position.coords.latitude;
+      this.getAddress(longitude, latitude);
+    });
+  }
+
+  private getAddress(longitude: number, latitude: number): void {
+    this.geojsonService.getAddressByCoord(longitude, latitude).subscribe(
+      (location) => (this.currentLocation = location),
+      (err) => console.error(err)
+    );
+  }
 }
diff --git a/src/app/map/components/map.component.ts b/src/app/map/components/map.component.ts
index f63314cb9..f873273fa 100644
--- a/src/app/map/components/map.component.ts
+++ b/src/app/map/components/map.component.ts
@@ -4,7 +4,7 @@ import { Observable } from 'rxjs';
 import { mergeMap } from 'rxjs/operators';
 import { Structure } from '../../models/structure.model';
 import { GeoJson } from '../models/geojson.model';
-import { GeojsonService } from '../services/geojson.service';
+import { GeojsonService } from '../../services/geojson.service';
 import { MapService } from '../services/map.service';
 
 @Component({
@@ -21,11 +21,9 @@ export class MapComponent implements OnChanges {
   public locateOptions = {
     flyTo: false,
     keepCurrentZoomLevel: false,
-    locateOptions: {
-      enableHighAccuracy: true,
-    },
     icon: 'fa-map-marker',
     clickBehavior: { inView: 'stop', outOfView: 'setView', inViewNotFollowing: 'setView' },
+    circlePadding: [5, 5],
   };
 
   constructor(private mapService: MapService, private geoJsonService: GeojsonService) {
@@ -77,7 +75,7 @@ export class MapComponent implements OnChanges {
    * @param idVoie Street reference
    */
   public getCoord(idVoie: number): Observable<GeoJson> {
-    return this.geoJsonService.getAddress(idVoie).pipe(mergeMap((res) => this.geoJsonService.getCoord(res)));
+    return this.geoJsonService.getAddressByIdVoie(idVoie).pipe(mergeMap((res) => this.geoJsonService.getCoord(res)));
   }
 
   /**
diff --git a/src/app/map/services/geojson.service.ts b/src/app/map/services/geojson.service.ts
deleted file mode 100644
index 7af9e3481..000000000
--- a/src/app/map/services/geojson.service.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-import { HttpClient, HttpHeaders } from '@angular/common/http';
-import { Injectable } from '@angular/core';
-import { Observable } from 'rxjs';
-import { map } from 'rxjs/operators';
-import { Address } from '../models/address.model';
-import { GeoJson } from '../models/geojson.model';
-
-@Injectable({
-  providedIn: 'root',
-})
-export class GeojsonService {
-  constructor(private http: HttpClient) {}
-
-  /**
-   * Retrive an address with a street national reference
-   * @param idVoie Number
-   */
-  public getAddress(idVoie: number): Observable<Address> {
-    return this.http
-      .get('/base-adresse/base-adresse-nationale/streets' + '?id=' + idVoie)
-      .pipe(map((data: { data: any[]; err: number }) => new Address(data.data[0])));
-  }
-
-  /**
-   * Get GeoLocation with an address
-   * @param address Address
-   */
-  public getCoord(address: Address): Observable<GeoJson> {
-    return this.http
-      .get('/geocoding/photon/api' + '?q=' + address.queryString())
-      .pipe(map((data: { features: any[]; type: string }) => new GeoJson(data.features[0])));
-  }
-}
diff --git a/src/app/map/models/address.model.ts b/src/app/models/address.model.ts
similarity index 100%
rename from src/app/map/models/address.model.ts
rename to src/app/models/address.model.ts
diff --git a/src/app/map/services/geojson.service.spec.ts b/src/app/services/geojson.service.spec.ts
similarity index 96%
rename from src/app/map/services/geojson.service.spec.ts
rename to src/app/services/geojson.service.spec.ts
index 359674551..8695016a7 100644
--- a/src/app/map/services/geojson.service.spec.ts
+++ b/src/app/services/geojson.service.spec.ts
@@ -24,7 +24,7 @@ describe('GeojsonService', () => {
 
   it('should get address for id 26061 ', async () => {
     await new Promise((resolve) => {
-      service.getAddress(26061).subscribe(
+      service.getAddressByIdVoie(26061).subscribe(
         (val) => {
           expect(val.zipcode).toEqual('69800');
           expect(val.text).toEqual('13ème Rue Cité Berliet');
diff --git a/src/app/services/geojson.service.ts b/src/app/services/geojson.service.ts
new file mode 100644
index 000000000..39aed758f
--- /dev/null
+++ b/src/app/services/geojson.service.ts
@@ -0,0 +1,99 @@
+import { HttpClient, HttpHeaders } from '@angular/common/http';
+import { Injectable } from '@angular/core';
+import { Observable } from 'rxjs';
+import { map } from 'rxjs/operators';
+import { Address } from '../models/address.model';
+import { GeoJson } from '../map/models/geojson.model';
+
+@Injectable({
+  providedIn: 'root',
+})
+export class GeojsonService {
+  constructor(private http: HttpClient) {}
+
+  /**
+   * Retrive an address with a street national reference
+   * @param idVoie Number
+   */
+  public getAddressByIdVoie(idVoie: number): Observable<Address> {
+    return this.http
+      .get('/base-adresse/base-adresse-nationale/streets' + '?id=' + idVoie)
+      .pipe(map((data: { data: any[]; err: number }) => new Address(data.data[0])));
+  }
+
+  /**
+   * Retrive an address by geolocation
+   * @param idVoie Number
+   */
+  public getAddressByCoord(longitude: number, latitude: number): Observable<any> {
+    return this.http
+      .get('/reverse/' + '?lon=' + longitude + '&lat=' + latitude)
+      .pipe(map((data: { features: any[] }) => new GeoJson(data.features[0])));
+  }
+
+  /**
+   * Get GeoLocation with an address
+   * @param address Address
+   */
+  public getCoord(address: Address): Observable<GeoJson> {
+    return this.http
+      .get('/geocoding/photon/api' + '?q=' + address.queryString())
+      .pipe(map((data: { features: any[]; type: string }) => new GeoJson(data.features[0])));
+  }
+
+  // :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+  // :::                                                                         :::
+  // :::  This routine calculates the distance between two points (given the     :::
+  // :::  latitude/longitude of those points). It is being used to calculate     :::
+  // :::  the distance between two locations using GeoDataSource (TM) prodducts  :::
+  // :::                                                                         :::
+  // :::  Definitions:                                                           :::
+  // :::    South latitudes are negative, east longitudes are positive           :::
+  // :::                                                                         :::
+  // :::  Passed to function:                                                    :::
+  // :::    lat1, lon1 = Latitude and Longitude of point 1 (in decimal degrees)  :::
+  // :::    lat2, lon2 = Latitude and Longitude of point 2 (in decimal degrees)  :::
+  // :::    unit = the unit you desire for results                               :::
+  // :::           where: 'M' is statute miles (default)                         :::
+  // :::                  'K' is kilometers                                      :::
+  // :::                  'N' is nautical miles                                  :::
+  // :::                                                                         :::
+  // :::  Worldwide cities and other features databases with latitude longitude  :::
+  // :::  are available at https://www.geodatasource.com                         :::
+  // :::                                                                         :::
+  // :::  For enquiries, please contact sales@geodatasource.com                  :::
+  // :::                                                                         :::
+  // :::  Official Web site: https://www.geodatasource.com                       :::
+  // :::                                                                         :::
+  // :::               GeoDataSource.com (C) All Rights Reserved 2018            :::
+  // :::                                                                         :::
+  // :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+
+  public getDistance(lat1, lon1, lat2, lon2, unit): string {
+    if (lat1 === lat2 && lon1 === lon2) {
+      return '0';
+    } else {
+      const radlat1 = (Math.PI * lat1) / 180;
+      const radlat2 = (Math.PI * lat2) / 180;
+      const theta = lon1 - lon2;
+      const radtheta = (Math.PI * theta) / 180;
+      let dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
+      if (dist > 1) {
+        dist = 1;
+      }
+      dist = Math.acos(dist);
+      dist = (dist * 180) / Math.PI;
+      dist = dist * 60 * 1.1515;
+      if (unit === 'K') {
+        dist = dist * 1.609344;
+      }
+      if (unit === 'M') {
+        dist = dist * 1.609344 * 1000;
+      }
+      if (unit === 'N') {
+        dist = dist * 0.8684;
+      }
+      return dist.toFixed(0);
+    }
+  }
+}
diff --git a/src/app/structure-list/components/card/card.component.html b/src/app/structure-list/components/card/card.component.html
index b8d0c1dc5..53f6dbb02 100644
--- a/src/app/structure-list/components/card/card.component.html
+++ b/src/app/structure-list/components/card/card.component.html
@@ -3,7 +3,7 @@
 
   <div class="headerStructure" fxLayout="row" fxLayoutAlign="space-between center">
     <span class="typeStructure">{{ structure.typeDeStructure }}</span>
-    <span class="distanceStructure">├─┤ 63 m</span>
+    <span *ngIf="geolocation" class="distanceStructure">├─┤ {{ distance }}</span>
   </div>
   <br />
   <div class="statusStructure" fxLayout="row" fxLayoutAlign="start center">
diff --git a/src/app/structure-list/components/card/card.component.ts b/src/app/structure-list/components/card/card.component.ts
index 9049bcfa7..1448989d5 100644
--- a/src/app/structure-list/components/card/card.component.ts
+++ b/src/app/structure-list/components/card/card.component.ts
@@ -1,14 +1,58 @@
-import { Component, Input, OnInit } from '@angular/core';
+import { Component, Input, OnInit, OnChanges, SimpleChanges } from '@angular/core';
 import { Structure } from '../../../models/structure.model';
+import { GeojsonService } from '../../../services/geojson.service';
+import { GeoJson } from '../../../map/models/geojson.model';
+import { Observable } from 'rxjs';
+import { mergeMap } from 'rxjs/operators';
 
 @Component({
   selector: 'app-card',
   templateUrl: './card.component.html',
   styleUrls: ['./card.component.scss'],
 })
-export class CardComponent implements OnInit {
+export class CardComponent implements OnInit, OnChanges {
   @Input() public structure: Structure;
-  constructor() {}
+  @Input() public geolocation: GeoJson;
+  public distance: string;
 
+  constructor(private geoJsonService: GeojsonService) {}
   ngOnInit(): void {}
+
+  ngOnChanges(changes: SimpleChanges): void {
+    if (changes.geolocation.currentValue) {
+      this.getStructurePosition();
+    }
+  }
+
+  /**
+   * Get structures positions and add marker corresponding to those positons on the map
+   */
+  private getStructurePosition(): void {
+    this.getCoord(this.structure.voie).subscribe((coord: GeoJson) => {
+      this.distance = this.geoJsonService.getDistance(
+        coord.geometry.getLon(),
+        coord.geometry.getLat(),
+        this.geolocation.geometry.getLon(),
+        this.geolocation.geometry.getLat(),
+        'M'
+      );
+      this.formatDistance();
+    });
+  }
+
+  private formatDistance(): void {
+    if (this.distance.length > 3) {
+      this.distance = (parseInt(this.distance, 10) / 1000).toFixed(1).toString() + ' km';
+    } else {
+      this.distance += ' m';
+    }
+  }
+
+  /**
+   * Get coord with a street reference
+   * @param idVoie Street reference
+   */
+  public getCoord(idVoie: number): Observable<GeoJson> {
+    return this.geoJsonService.getAddressByIdVoie(idVoie).pipe(mergeMap((res) => this.geoJsonService.getCoord(res)));
+  }
 }
diff --git a/src/app/structure-list/components/recherche/recherche.component.ts b/src/app/structure-list/components/recherche/recherche.component.ts
index 7754a323b..6ccca06c4 100644
--- a/src/app/structure-list/components/recherche/recherche.component.ts
+++ b/src/app/structure-list/components/recherche/recherche.component.ts
@@ -1,4 +1,4 @@
-import { Component, OnInit } from '@angular/core';
+import { Component, OnInit, Input } from '@angular/core';
 
 @Component({
   selector: 'app-recherche',
diff --git a/src/app/structure-list/structure-list.component.html b/src/app/structure-list/structure-list.component.html
index 017b98518..843ba1f55 100644
--- a/src/app/structure-list/structure-list.component.html
+++ b/src/app/structure-list/structure-list.component.html
@@ -1,3 +1,3 @@
 <app-recherche></app-recherche>
 <span class="nbStructuresLabel">{{ structureList.length }} structures</span>
-<app-card *ngFor="let structure of structureList" [structure]="structure"></app-card>
+<app-card *ngFor="let structure of structureList" [structure]="structure" [geolocation]="location"></app-card>
diff --git a/src/app/structure-list/structure-list.component.ts b/src/app/structure-list/structure-list.component.ts
index 37296692d..4eee772a8 100644
--- a/src/app/structure-list/structure-list.component.ts
+++ b/src/app/structure-list/structure-list.component.ts
@@ -1,6 +1,6 @@
 import { Component, Input, OnInit } from '@angular/core';
 import { Structure } from '../models/structure.model';
-
+import { GeoJson } from '../map/models/geojson.model';
 @Component({
   selector: 'app-structure-list',
   templateUrl: './structure-list.component.html',
@@ -8,6 +8,7 @@ import { Structure } from '../models/structure.model';
 })
 export class StructureListComponent implements OnInit {
   @Input() public structureList: Structure[];
+  @Input() public location: GeoJson;
   constructor() {}
 
   ngOnInit(): void {}
-- 
GitLab