-
Notifications
You must be signed in to change notification settings - Fork 1
/
map.component.ts
340 lines (318 loc) · 12.3 KB
/
map.component.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
import { Component, EventEmitter, HostListener, Inject, Input, OnChanges, Output, SimpleChanges } from '@angular/core';
import L, { geoJSON, latLng, layerGroup, Map, MapOptions, tileLayer } from 'leaflet';
import * as _ from 'lodash';
import { GeometryPolygonConfiguration, GEOMETRY_POLYGON_TOKEN } from '../../configurations/geometry-polygon.configuration';
import { InitialPositionConfiguration, INITIAL_POSITION_TOKEN } from '../../configurations/initial-position.configuration';
import { MarkerTypeConfiguration, MARKER_TYPE_TOKEN } from '../../configurations/marker-type.configuration';
import { ZoomLevelConfiguration, ZOOM_LEVEL_TOKEN } from '../../configurations/zoom-level.configuration';
import { GeoJsonProperties } from '../models/geoJsonProperties.model';
import { Structure } from '../models/structure.model';
import { GeoJsonRepository, GEO_JSON_TOKEN } from '../repositories/geo-json.repository';
import { MapService } from './map.service';
@Component({
selector: 'app-map',
providers: [MapService],
templateUrl: './map.component.html',
styleUrls: ['./map.component.scss']
})
export class MapComponent implements OnChanges {
@Input() public isOrientationForm = false;
@Input() public structures: Structure[] = [];
@Input() public structuresToPrint: Structure[] = [];
@Input() public toogleToolTipId: string;
@Input() public selectedMarkerId: string;
@Input() public isMapPhone: boolean;
@Input() public searchedValue: string | [number, number];
@Output() public selectedStructure: EventEmitter<Structure> = new EventEmitter<Structure>();
@Output() public orientationButtonClick: EventEmitter<Structure> = new EventEmitter<Structure>();
private currentStructure: Structure;
public map: Map;
public mapOptions: MapOptions;
public zoomOptions = { animate: true, duration: 0.5 };
// Add listener on the popup button to show details of structure
@HostListener('document:click', ['$event'])
public clickout(event): void {
if (event.target.classList.contains('btnShowDetails')) {
this.selectedStructure.emit(this.currentStructure);
}
if (event.target.classList.contains('add')) {
this.orientationButtonClick.emit(this.currentStructure);
this.getStructuresPositions(this.structures);
}
}
constructor(
@Inject(GEOMETRY_POLYGON_TOKEN)
private readonly metropole: GeometryPolygonConfiguration,
@Inject(MARKER_TYPE_TOKEN)
private readonly markerType: MarkerTypeConfiguration,
@Inject(ZOOM_LEVEL_TOKEN)
private readonly zoomLevel: ZoomLevelConfiguration,
@Inject(INITIAL_POSITION_TOKEN)
private readonly initialPosition: InitialPositionConfiguration,
@Inject(GEO_JSON_TOKEN) private readonly geoJsonService: GeoJsonRepository,
private readonly mapService: MapService
) {
this.initializeMapOptions();
}
ngOnChanges(changes: SimpleChanges): void {
if (changes.searchedValue && !changes.searchedValue.firstChange) {
if (changes.searchedValue.currentValue) {
this.processTownCoordinate(changes.searchedValue.currentValue);
} else {
this.map.setView(this.mapOptions.center, this.mapOptions.zoom);
}
}
if (changes.isMapPhone) {
if (this.isMapPhone) {
setTimeout(() => {
this.map.invalidateSize();
}, 0);
}
}
if (changes.structures && this.map) {
this.handleStructurePosition(changes.structures.previousValue);
}
// Handle map marker tooltip
if (changes.toogleToolTipId && changes.toogleToolTipId.currentValue !== changes.toogleToolTipId.previousValue) {
if (changes.toogleToolTipId.previousValue !== undefined) {
if (this.isToPrint(changes.toogleToolTipId.previousValue)) {
this.mapService.setAddedToListMarker(
changes.toogleToolTipId.previousValue,
this.getMarkerTypeByStructureId(changes.toogleToolTipId.previousValue)
);
} else {
this.mapService.setUnactiveMarker(
changes.toogleToolTipId.previousValue,
this.getMarkerTypeByStructureId(changes.toogleToolTipId.previousValue)
);
}
}
if (changes.toogleToolTipId.currentValue !== undefined) {
this.mapService.setActiveMarker(
changes.toogleToolTipId.currentValue,
this.getMarkerTypeByStructureId(changes.toogleToolTipId.currentValue)
);
}
}
// Handle map marker if none selected
if (changes.selectedMarkerId && this.map) {
this.map.closePopup();
if (changes.selectedMarkerId.currentValue === undefined) {
this.mapService.setDefaultMarker(
changes.selectedMarkerId.previousValue,
this.getMarkerTypeByStructureId(changes.selectedMarkerId.previousValue)
);
this.map.setView(this.mapOptions.center, this.mapOptions.zoom);
}
}
// Handle map marker if one is set with url or selected
if (this.mapService.getMarker(this.selectedMarkerId)) {
this.mapService.setSelectedMarker(this.selectedMarkerId, this.getMarkerTypeByStructureId(this.selectedMarkerId));
this.centerLeafletMapOnMarker(this.selectedMarkerId);
}
this.closePreviousMarker(changes);
if (changes.structuresToPrint) {
if (changes.structuresToPrint.currentValue < changes.structuresToPrint.previousValue) {
this.mapService?.setUnactiveMarker(
this.toogleToolTipId,
this.getMarkerTypeByStructureId(changes.structuresToPrint.previousValue)
);
}
this.structuresToPrint.forEach((structure: Structure) => {
this.mapService.setAddedToListMarker(structure._id, this.getMarkerTypeByStructureId(structure._id));
});
}
}
public processTownCoordinate(queryString: string): void {
this.geoJsonService.getTownshipCoord(queryString).subscribe(
(townData) => {
if (townData.length > 0) {
const bounds = new L.LatLngBounds(townData.map((dataArray) => dataArray.reverse()));
this.map.fitBounds(bounds);
}
},
(err) => {
this.map.flyTo(this.mapOptions.center, this.mapOptions.zoom, this.zoomOptions);
}
);
}
/**
* Create a user position marcker and center the map on it with a zoom level defined in ZoomLevel
* @param coords {[number, number]} Map center position
*/
public centerOnCoordinates(coords: [number, number]): void {
this.mapService.createMarker(coords[1], coords[0], this.markerType.user, 'userLocation').addTo(this.map);
this.map.flyTo(new L.LatLng(coords[1], coords[0]), this.zoomLevel.userPosition, this.zoomOptions);
}
/**
* Get structures positions and add marker corresponding to those positons on the map
*/
private handleStructurePosition(previousStructuresValue: Structure[]): void {
// If there is more structure than before, append them
if (
previousStructuresValue &&
previousStructuresValue.length > 0 &&
previousStructuresValue.length < this.structures.length
) {
this.getStructuresPositions(_.differenceWith(this.structures, previousStructuresValue, _.isEqual));
} else if (this.structures) {
this.map = this.mapService.cleanMap(this.map);
this.getStructuresPositions(this.structures);
this.structuresToPrint.forEach((structure: Structure) => {
this.mapService.setAddedToListMarker(structure._id, this.getMarkerTypeByStructureId(structure._id));
});
}
}
private isToPrint(id: string): boolean {
return this.structuresToPrint.findIndex((elem) => elem._id == id) > -1 ? true : false;
}
/**
* Returns according marker type base on {MarkerType}
* @param {Structure} structure
* @returns {number}
*/
private getMarkerType(structure: Structure): number {
return structure?.labelsQualifications?.includes('conseillerNumFranceServices')
? this.markerType.conseillerFrance
: this.markerType.structure;
}
/**
* Return the map marker type given a structure id
* @param {string} id - Structure id
* @returns {number}
*/
private getMarkerTypeByStructureId(id: string): number {
return this.getMarkerType(this.structures.find((structure) => structure._id === id));
}
private getStructuresPositions(structureList: Structure[]): void {
for (const structure of structureList) {
this.mapService
.createMarker(
structure.getLat(),
structure.getLon(),
this.getMarkerType(structure),
structure._id,
this.buildToolTip(structure)
)
.addTo(this.map)
// store structure before user click on button
.on('popupopen', () => {
this.currentStructure = structure;
});
}
}
/**
* Create tooltip for display
* @param structure Structure
*/
private buildToolTip(structure: Structure): string {
let cssAvailabilityClass = structure.isOpen ? 'available' : null;
if (cssAvailabilityClass === null) {
if (structure.openedOn.day) {
cssAvailabilityClass = 'unavailable';
} else {
cssAvailabilityClass = 'unknown';
}
}
return (
'<h1>' +
structure.structureName +
'</h1>' +
'<p>' +
structure.getLabelTypeStructure() +
'</p>' +
(this.isOrientationForm
? '<div class="pop-up orientation"><button type="button" class="orientationButton btnShowDetails"><span class="ico-gg-eye-alt eye"></span>Voir</button></div>'
: '<div class="pop-up"><button type="button" class="btnShowDetails">Voir</button></div>')
);
}
private buildMdmPopUp(mdmProperties: GeoJsonProperties): string {
return `<h1>${mdmProperties.nom}</h1><p>${mdmProperties.adresse}</p>`;
}
/**
* Add marker when map is ready to be showned
* @param map map
*/
public onMapReady(map: Map): void {
this.map = map;
if (this.searchedValue) {
if (Array.isArray(this.searchedValue)) {
this.centerOnCoordinates(this.searchedValue);
}
}
}
/**
* Init map options :
* - Metropole bounds based on a WMS service hosted by data.grandlyon.com
* - Map Layer based on open street maps
*/
private initializeMapOptions(): void {
// Init mdm
this.initMDMLayer();
// Init WMS service with param from data.grandlyon.com
layerGroup();
const carteLayer = tileLayer('https://{s}.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}{r}.png', {
attribution: '© <a href="https://carto.com/attributions">CARTO</a>',
maxZoom: this.zoomLevel.max
});
// Center is set on townhall
// Zoom is blocked on 11 to prevent people to zoom out from metropole
this.mapOptions = {
center: latLng(this.initialPosition.latitude, this.initialPosition.longitude),
maxZoom: this.zoomLevel.max,
zoom: this.zoomLevel.regular,
minZoom: this.zoomLevel.min,
layers: [carteLayer]
};
}
private initMDMLayer(): void {
this.geoJsonService.getMDMGeoJson().subscribe((res) => {
res.forEach((mdm) => {
this.mapService
.createMarker(
mdm.geometry.getLat(),
mdm.geometry.getLon(),
this.markerType.mdm,
null,
this.buildMdmPopUp(mdm.properties)
)
.addTo(this.map);
});
this.initMetropoleLayer();
});
}
private centerLeafletMapOnMarker(markerId: string): void {
if (this.mapService.getMarker(markerId)) {
const marker = this.mapService.getMarker(markerId);
const latLngs = marker.getLatLng();
this.map.flyTo(new L.LatLng(latLngs.lat, latLngs.lng), this.zoomLevel.max, this.zoomOptions);
}
}
private initMetropoleLayer(): void {
this.map.addLayer(
geoJSON(
{
type: this.metropole.features[0].geometry.type,
coordinates: this.metropole.features[0].geometry.coordinates
} as any,
{ style: () => ({ color: '#a00000', fillOpacity: 0, weight: 1 }) }
)
);
}
/**
* Close previous markers
* - if strucure is closed
* - if a new marker is selected
*/
private closePreviousMarker(changes: SimpleChanges): void {
if (
(changes.selectedMarkerId?.currentValue === undefined && changes.selectedMarkerId?.previousValue) ||
changes.selectedMarkerId?.currentValue !== changes.selectedMarkerId?.previousValue
) {
this.mapService.setUnactiveMarker(
changes.selectedMarkerId.previousValue,
this.getMarkerTypeByStructureId(changes.selectedMarkerId.previousValue)
);
}
}
}