-
Notifications
You must be signed in to change notification settings - Fork 416
/
Copy pathMap.jsx
594 lines (549 loc) · 23.9 KB
/
Map.jsx
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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
/**
* Copyright 2015, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
import L from 'leaflet';
import PropTypes from 'prop-types';
import React from 'react';
import ConfigUtils from '../../../utils/ConfigUtils';
import {reprojectBbox, reproject} from '../../../utils/CoordinatesUtils';
import assign from 'object-assign';
import {
getGoogleMercatorResolutions,
EXTENT_TO_ZOOM_HOOK,
RESOLUTIONS_HOOK,
COMPUTE_BBOX_HOOK,
GET_PIXEL_FROM_COORDINATES_HOOK,
GET_COORDINATES_FROM_PIXEL_HOOK,
ZOOM_TO_EXTENT_HOOK,
registerHook
} from '../../../utils/MapUtils';
import Rx from 'rxjs';
import {throttle} from 'lodash';
import 'leaflet/dist/leaflet.css';
import './SingleClick';
class LeafletMap extends React.Component {
static propTypes = {
id: PropTypes.string,
document: PropTypes.object,
center: ConfigUtils.PropTypes.center,
zoom: PropTypes.number.isRequired,
viewerOptions: PropTypes.object,
mapStateSource: ConfigUtils.PropTypes.mapStateSource,
style: PropTypes.object,
projection: PropTypes.string,
onMapViewChanges: PropTypes.func,
onClick: PropTypes.func,
onRightClick: PropTypes.func,
mapOptions: PropTypes.object,
limits: PropTypes.object,
zoomControl: PropTypes.bool,
mousePointer: PropTypes.string,
onMouseMove: PropTypes.func,
onLayerLoading: PropTypes.func,
onLayerLoad: PropTypes.func,
onLayerError: PropTypes.func,
resize: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
measurement: PropTypes.object,
changeMeasurementState: PropTypes.func,
registerHooks: PropTypes.bool,
interactive: PropTypes.bool,
resolutions: PropTypes.array,
hookRegister: PropTypes.object,
onCreationError: PropTypes.func,
onMouseOut: PropTypes.func,
onResolutionsChange: PropTypes.func
};
static defaultProps = {
id: 'map',
onMapViewChanges: () => {},
onCreationError: () => {},
onClick: null,
onMouseMove: () => {},
zoomControl: true,
mapOptions: {
zoomAnimation: true,
attributionControl: false
},
projection: "EPSG:3857",
center: {x: 13, y: 45, crs: "EPSG:4326"},
zoom: 5,
onLayerLoading: () => {},
onLayerLoad: () => {},
onLayerError: () => {},
resize: 0,
registerHooks: true,
hookRegister: {
registerHook
},
style: {},
interactive: true,
resolutions: getGoogleMercatorResolutions(0, 23),
onMouseOut: () => {},
onResolutionsChange: () => {}
};
state = { };
UNSAFE_componentWillMount() {
this.zoomOffset = 0;
if (this.props.mapOptions && this.props.mapOptions.view && this.props.mapOptions.view.resolutions && this.props.mapOptions.view.resolutions.length > 0) {
const scaleFun = L.CRS.EPSG3857.scale;
const ratio = this.props.mapOptions.view.resolutions[0] / getGoogleMercatorResolutions(0, 23)[0];
this.crs = assign({}, L.CRS.EPSG3857, {
scale: (zoom) => {
return scaleFun.call(L.CRS.EPSG3857, zoom) / Math.pow(2, Math.round(Math.log2(ratio)));
}
});
this.zoomOffset = Math.round(Math.log2(ratio));
}
}
componentDidMount() {
const {limits = {}} = this.props;
const maxBounds = limits.restrictedExtent && limits.crs && reprojectBbox(limits.restrictedExtent, limits.crs, "EPSG:4326");
let mapOptions = assign({}, this.props.interactive ? {} : {
dragging: false,
touchZoom: false,
scrollWheelZoom: false,
doubleClickZoom: false,
boxZoom: false,
tap: false,
attributionControl: false,
maxBounds: maxBounds && L.latLngBounds([
[maxBounds[1], maxBounds[0]],
[maxBounds[3], maxBounds[2]]
]),
maxBoundsViscosity: maxBounds && 1.0,
minZoom: limits && limits.minZoom,
maxZoom: limits && limits.maxZoom || 23
}, this.props.mapOptions, this.crs ? {crs: this.crs} : {});
// it is not possible to use #<id> in a query selector if the id starts with a number
const map = L.map(this.getDocument().querySelector(`[id='${this.props.id}'] > .map-viewport`), assign({ zoomControl: false }, mapOptions) ).setView([this.props.center.y, this.props.center.x],
Math.round(this.props.zoom));
this.map = map;
if (this.props.registerHooks) {
this.registerHooks();
}
// store zoomControl in the class to target the right control while add/remove
if (this.props.zoomControl) {
this.mapZoomControl = L.control.zoom();
this.map.addControl(this.mapZoomControl);
}
this.attribution = L.control.attribution();
this.attribution.addTo(this.map);
const mapDocument = this.getDocument();
if (this.props.mapOptions.attribution && this.props.mapOptions.attribution.container) {
mapDocument.querySelector(this.props.mapOptions.attribution.container).appendChild(this.attribution.getContainer());
if (mapDocument.querySelector('.leaflet-control-container .leaflet-control-attribution')) {
mapDocument.querySelector('.leaflet-control-container .leaflet-control-attribution').parentNode.removeChild(mapDocument.querySelector('.leaflet-control-container .leaflet-control-attribution'));
}
}
this.map.on('moveend', this.updateMapInfoState);
// this uses the hook defined in ./SingleClick.js for leaflet 0.7.*
this.map.on('singleclick', (event) => {
if (this.props.onClick) {
const intersectedFeatures = this.getIntersectedFeatures(map, event.latlng);
this.props.onClick({
pixel: {
x: event.containerPoint.x,
y: event.containerPoint.y
},
latlng: {
lat: event.latlng.lat,
lng: event.latlng.lng,
z: this.getElevation(event.latlng, event.containerPoint)
},
rawPos: [event.latlng.lat, event.latlng.lng],
modifiers: {
alt: event.originalEvent.altKey,
ctrl: event.originalEvent.ctrlKey,
metaKey: event.originalEvent.metaKey, // MAC OS
shift: event.originalEvent.shiftKey
},
intersectedFeatures
});
}
});
const mouseMove = throttle(this.mouseMoveEvent, 100);
this.map.on('dragstart', () => { this.map.off('mousemove', mouseMove); });
this.map.on('dragend', () => { this.map.on('mousemove', mouseMove); });
this.map.on('mousemove', mouseMove);
this.map.on('contextmenu', () => {
if (this.props.onRightClick) {
this.props.onRightClick(event.containerPoint);
}
});
// The timeout is needed to cover the delay we have for the throttled mouseMove event.
this.map.on('mouseout', () => {
setTimeout(() => this.props.onMouseOut(), 150);
});
this.updateMapInfoState();
this.setMousePointer(this.props.mousePointer);
// NOTE: this re-call render function after div creation to have the map initialized.
this.forceUpdate();
this.props.onResolutionsChange(this.getResolutions());
this.map.on('layeradd', (event) => {
// we want to run init code only the first time a layer is added to the map
if (event.layer._ms2Added) {
const isStopped = event.layer.layerLoadingStream$ && event.layer.layerLoadingStream$.isStopped;
this.addLayerObservable(event, isStopped);
return;
}
event.layer._ms2Added = true;
// avoid binding if not possible, e.g. for measurement vector layers
if (!event.layer.layerId) {
return;
}
if (event.layer && event.layer.options && event.layer.options.msLayer === 'vector') {
return;
}
if (event && event.layer && event.layer.on ) {
// TODO check event.layer.on is a function
// Needed to fix GeoJSON Layer neverending loading
this.addLayerObservable(event, true);
if (!(event.layer.options && event.layer.options.hideLoading)) {
this.props.onLayerLoading(event.layer.layerId);
event.layer.layerLoadingStream$.next();
}
event.layer.on('loading', (loadingEvent) => {
this.props.onLayerLoading(loadingEvent.target.layerId);
event.layer.layerLoadingStream$.next();
});
event.layer.on('load', (loadEvent) => {
this.props.onLayerLoad(loadEvent.target.layerId);
event.layer.layerLoadStream$.next();
});
event.layer.on('tileloadstart ', () => { event.layer._ms2LoadingTileCount++; });
if (event.layer.options && !event.layer.options.hideErrors || !event.layer.options) {
event.layer.on('tileerror', (errorEvent) => { event.layer.layerErrorStream$.next(errorEvent); });
}
// WFS data
event.layer.on('loaderror', (error) => {
this.props.onLayerError(error.target.layerId);
});
}
});
this.map.on('layerremove', (event) => {
if (event.layer.layerLoadingStream$) {
event.layer.layerLoadingStream$.complete();
event.layer.layerLoadStream$.complete();
event.layer.layerErrorStream$.complete();
}
});
this.drawControl = null;
}
UNSAFE_componentWillReceiveProps(newProps) {
if (newProps.mousePointer !== this.props.mousePointer) {
this.setMousePointer(newProps.mousePointer);
}
// update the position if the map is not the source of the state change
if (this.map && newProps.mapStateSource !== this.props.id) {
this._updateMapPositionFromNewProps(newProps);
}
if (newProps.zoomControl !== this.props.zoomControl) {
if (newProps.zoomControl) {
this.mapZoomControl = L.control.zoom();
this.map.addControl(this.mapZoomControl);
} else if (this.mapZoomControl && !newProps.zoomControl) {
this.map.removeControl(this.mapZoomControl);
this.mapZoomControl = undefined;
}
}
if (newProps.resize !== this.props.resize) {
setTimeout(() => {
if (this.map) {
this.map.invalidateSize(false);
}
}, 0);
}
// update map limits
if (this.props.limits !== newProps.limits) {
const {limits = {}} = newProps;
const {limits: oldLimits} = this.props;
if (limits.restrictedExtent !== (oldLimits && oldLimits.restrictedExtent)) {
const maxBounds = limits.restrictedExtent && limits.crs && reprojectBbox(limits.restrictedExtent, limits.crs, "EPSG:4326");
this.map.setMaxBounds(limits.restrictedExtent && L.latLngBounds([
[maxBounds[1], maxBounds[0]],
[maxBounds[3], maxBounds[2]]
]));
}
if (limits.minZoom !== (oldLimits && oldLimits.minZoom)) {
this.map.setMinZoom(limits.minZoom);
}
this.props.onResolutionsChange(this.getResolutions());
}
return false;
}
componentWillUnmount() {
const mapDocument = this.getDocument();
const attributionContainer = this.props.mapOptions.attribution && this.props.mapOptions.attribution.container && mapDocument.querySelector(this.props.mapOptions.attribution.container);
if (attributionContainer && this.attribution.getContainer() && attributionContainer.querySelector('.leaflet-control-attribution')) {
try {
attributionContainer.removeChild(this.attribution.getContainer());
} catch (e) {
// do nothing... probably an old configuration
}
}
if (this.mapZoomControl) {
this.map.removeControl(this.mapZoomControl);
this.mapZoomControl = undefined;
}
// remove all events
this.map.off();
// remove map and set to undefined for setTimeout for .invalidateSize action
this.map.remove();
this.map = undefined;
}
getDocument = () => {
return this.props.document || document;
};
getResolutions = () => {
return this.props.resolutions;
};
getIntersectedFeatures = (map, latlng) => {
let groupIntersectedFeatures = {};
const clickBounds = L.latLngBounds(latlng, latlng);
map.eachLayer((layer) => {
if (layer?.layerId && layer?.eachLayer) {
layer.eachLayer(feature => {
const centerBounds = feature?.getLatLng
? L.latLngBounds(feature.getLatLng(), feature.getLatLng())
: null;
const bounds = feature?.getBounds
? feature.getBounds()
: centerBounds;
if (bounds && feature?.toGeoJSON) {
if (bounds && clickBounds.intersects(bounds)) {
const geoJSONFeature = feature.toGeoJSON();
groupIntersectedFeatures[layer.layerId] = groupIntersectedFeatures[layer.layerId]
? [ ...groupIntersectedFeatures[layer.layerId], geoJSONFeature ]
: [ geoJSONFeature ];
}
}
});
}
});
return Object.keys(groupIntersectedFeatures).map(id => ({ id, features: groupIntersectedFeatures[id] }));
}
getElevation(pos, containerPoint) {
const elevationLayers = this.map.msElevationLayers || [];
return elevationLayers?.[0]?.getElevation
? elevationLayers[0].getElevation(pos, containerPoint)
: undefined;
}
render() {
const map = this.map;
const mapProj = this.props.projection;
const children = map ? React.Children.map(this.props.children, child => {
return child ? React.cloneElement(child, {
map: map,
projection: mapProj,
zoomOffset: this.zoomOffset,
onCreationError: this.props.onCreationError,
onClick: this.props.onClick,
resolutions: this.getResolutions(),
zoom: this.props.zoom
}) : null;
}) : null;
return (
<div id={this.props.id} style={this.props.style}>
<div
className="map-viewport"
style={{
position: 'relative',
overflow: 'hidden',
width: '100%',
height: '100%'
}}
></div>
{children}
</div>
);
}
_updateMapPositionFromNewProps = (newProps) => {
// current implementation will update the map only if the movement
// between 12 decimals in the reference system to avoid rounded value
// changes due to float mathematic operations.
const isNearlyEqual = function(a, b) {
if (a === undefined || b === undefined) {
return false;
}
return a.toFixed(12) - b.toFixed(12) === 0;
};
// getting all centers we need to check
const newCenter = newProps.center;
const currentCenter = this.props.center;
const mapCenter = this.map.getCenter();
// checking if the current props are the same
const propsCentersEqual = isNearlyEqual(newCenter.x, currentCenter.x) &&
isNearlyEqual(newCenter.y, currentCenter.y);
// if props are the same nothing to do, otherwise
// we need to check if the new center is equal to map center
const centerIsNotUpdated = propsCentersEqual ||
isNearlyEqual(newCenter.x, mapCenter.lng) &&
isNearlyEqual(newCenter.y, mapCenter.lat);
// getting all zoom values we need to check
const newZoom = newProps.zoom;
const currentZoom = this.props.zoom;
const mapZoom = this.map.getZoom();
// checking if the current props are the same
const propsZoomEqual = newZoom === currentZoom;
// if props are the same nothing to do, otherwise
// we need to check if the new zoom is equal to map zoom
const zoomIsNotUpdated = propsZoomEqual || newZoom === mapZoom;
// do the change at the same time, to avoid glitches
if (!centerIsNotUpdated && !zoomIsNotUpdated) {
this.map.setView([newProps.center.y, newProps.center.x], Math.round(newProps.zoom));
} else if (!zoomIsNotUpdated) {
this.map.setZoom(newProps.zoom);
} else if (!centerIsNotUpdated) {
this.map.setView([newProps.center.y, newProps.center.x]);
}
};
updateMapInfoState = () => {
const bbox = this.map.getBounds().toBBoxString().split(',');
const size = {
height: this.map.getSize().y,
width: this.map.getSize().x
};
const center = this.map.getCenter();
const zoom = this.map.getZoom();
const viewerOptions = this.props.viewerOptions;
this.props.onMapViewChanges(
{
x: center.lng,
y: center.lat,
crs: "EPSG:4326"
},
zoom,
{
bounds: {
minx: parseFloat(bbox[0]),
miny: parseFloat(bbox[1]),
maxx: parseFloat(bbox[2]),
maxy: parseFloat(bbox[3])
},
crs: 'EPSG:4326',
rotation: 0
},
size,
this.props.id,
this.props.projection,
viewerOptions, // viewerOptions
this.getResolutions()[Math.round(zoom)] // resolution
);
};
setMousePointer = (pointer) => {
if (this.map) {
const mapDiv = this.map.getContainer();
mapDiv.style.cursor = pointer || 'auto';
}
};
mouseMoveEvent = (event) => {
let pos = event.latlng.wrap();
const intersectedFeatures = this.getIntersectedFeatures(this.map, event.latlng);
this.props.onMouseMove({
x: pos.lng || 0.0,
y: pos.lat || 0.0,
z: this.getElevation(pos, event.containerPoint),
crs: "EPSG:4326",
pixel: {
x: event.containerPoint.x,
y: event.containerPoint.y
},
latlng: {
lat: event.latlng.lat,
lng: event.latlng.lng,
z: this.getElevation(event.latlng, event.containerPoint)
},
rawPos: [event.latlng.lat, event.latlng.lng],
intersectedFeatures
});
};
registerHooks = () => {
this.props.hookRegister.registerHook(EXTENT_TO_ZOOM_HOOK, (extent) => {
var repojectedPointA = reproject([extent[0], extent[1]], this.props.projection, 'EPSG:4326');
var repojectedPointB = reproject([extent[2], extent[3]], this.props.projection, 'EPSG:4326');
return this.map.getBoundsZoom([[repojectedPointA.y, repojectedPointA.x], [repojectedPointB.y, repojectedPointB.x]]) - 1;
});
this.props.hookRegister.registerHook(RESOLUTIONS_HOOK, () => {
return this.getResolutions();
});
this.props.hookRegister.registerHook(COMPUTE_BBOX_HOOK, (center, zoom) => {
let latLngCenter = L.latLng([center.y, center.x]);
// this call will use map internal size
let topLeftPoint = this.map._getNewPixelOrigin(latLngCenter, zoom);
let pixelBounds = new L.Bounds(topLeftPoint, topLeftPoint.add(this.map.getSize()));
let southWest = this.map.unproject(pixelBounds.getBottomLeft(), zoom);
let northEast = this.map.unproject(pixelBounds.getTopRight(), zoom);
let bbox = new L.LatLngBounds(southWest, northEast).toBBoxString().split(',');
return {
bounds: {
minx: parseFloat(bbox[0]),
miny: parseFloat(bbox[1]),
maxx: parseFloat(bbox[2]),
maxy: parseFloat(bbox[3])
},
crs: 'EPSG:4326',
rotation: 0
};
});
this.props.hookRegister.registerHook(GET_PIXEL_FROM_COORDINATES_HOOK, (pos) => {
let latLng = reproject(pos, this.props.projection, 'EPSG:4326');
let pixel = this.map.latLngToContainerPoint([latLng.y, latLng.x]);
return [pixel.x, pixel.y];
});
this.props.hookRegister.registerHook(GET_COORDINATES_FROM_PIXEL_HOOK, (pixel) => {
const point = this.map.containerPointToLatLng(pixel);
let pos = reproject([point.lng, point.lat], 'EPSG:4326', this.props.projection);
return [pos.x, pos.y];
});
this.props.hookRegister.registerHook(ZOOM_TO_EXTENT_HOOK, (extent, { padding, crs, maxZoom, duration } = {}) => {
const paddingTopLeft = padding && L.point(padding.left || 0, padding.top || 0);
const paddingBottomRight = padding && L.point(padding.right || 0, padding.bottom || 0);
const bounds = reprojectBbox(extent, crs, 'EPSG:4326');
// bbox is minx, miny, maxx, maxy'southwest_lng,southwest_lat,northeast_lng,northeast_lat'
this.map.fitBounds([
// sw
[bounds[1], bounds[0]],
// ne
[bounds[3], bounds[2]]
],
{
paddingTopLeft,
paddingBottomRight,
maxZoom,
duration,
animate: duration === 0 ? false : undefined
}
);
});
};
addLayerObservable = (event, stopped) => {
if (!event.layer.layerId
|| event.layer && event.layer.options && event.layer.options.msLayer === 'vector') {
return;
}
if (event && event.layer && event.layer.on && stopped) {
event.layer._ms2LoadingTileCount = 0;
event.layer.layerLoadingStream$ = new Rx.Subject();
event.layer.layerLoadStream$ = new Rx.Subject();
event.layer.layerErrorStream$ = new Rx.Subject();
event.layer.layerErrorStream$
.bufferToggle(
event.layer.layerLoadingStream$,
() => event.layer.layerLoadStream$)
.subscribe({
next: errorEvent => {
const loadingTileCount = event.layer._ms2LoadingTileCount || errorEvent && errorEvent.length || 0;
if (errorEvent && errorEvent.length > 0) {
this.props.onLayerError(errorEvent[0].target.layerId, loadingTileCount, errorEvent.length);
}
event.layer._ms2LoadingTileCount = 0;
}
});
}
};
}
export default LeafletMap;