-
-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathTaskMap.jsx
More file actions
798 lines (730 loc) · 25.6 KB
/
Copy pathTaskMap.jsx
File metadata and controls
798 lines (730 loc) · 25.6 KB
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
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
import booleanDisjoint from "@turf/boolean-disjoint";
import { featureCollection, point } from "@turf/helpers";
import { coordAll } from "@turf/meta";
import classNames from "classnames";
import L from "leaflet";
import _clone from "lodash/clone";
import _compact from "lodash/compact";
import _flatten from "lodash/flatten";
import _isEmpty from "lodash/isEmpty";
import _isObject from "lodash/isObject";
import _map from "lodash/map";
import _omit from "lodash/omit";
import _pick from "lodash/pick";
import _sortBy from "lodash/sortBy";
import PropTypes from "prop-types";
import React, { useState, useEffect, useMemo } from "react";
import ReactDOM from "react-dom";
import { IntlProvider } from "react-intl";
import {
AttributionControl,
LayerGroup,
MapContainer,
Pane,
useMap,
useMapEvents,
} from "react-leaflet";
import AsMappableTask from "../../../interactions/Task/AsMappableTask";
import AsIdentifiableFeature from "../../../interactions/TaskFeature/AsIdentifiableFeature";
import AsSimpleStyleableFeature, {
supportedSimplestyles,
} from "../../../interactions/TaskFeature/AsSimpleStyleableFeature";
import { DEFAULT_ZOOM, MAX_ZOOM } from "../../../services/Challenge/ChallengeZoom/ChallengeZoom";
import {
DEFAULT_OVERLAY_ORDER,
buildLayerSources,
} from "../../../services/VisibleLayer/LayerSources";
import BusySpinner from "../../BusySpinner/BusySpinner";
import DirectionalIndicationMarker from "../../EnhancedMap/DirectionalIndicationMarker/DirectionalIndicationMarker";
import ImageMarkerLayer from "../../EnhancedMap/ImageMarkerLayer/ImageMarkerLayer";
import MapAnimator from "../../EnhancedMap/MapAnimator/MapAnimator";
import OSMDataLayer from "../../EnhancedMap/OSMDataLayer/OSMDataLayer";
import PropertyList from "../../EnhancedMap/PropertyList/PropertyList";
import SourcedTileLayer from "../../EnhancedMap/SourcedTileLayer/SourcedTileLayer";
import TaskFeatureLayer from "../../EnhancedMap/TaskFeatureLayer/TaskFeatureLayer";
import WithIntersectingOverlays from "../../HOCs/WithIntersectingOverlays/WithIntersectingOverlays";
import WithKeyboardShortcuts from "../../HOCs/WithKeyboardShortcuts/WithKeyboardShortcuts";
import WithMapillaryImages from "../../HOCs/WithMapillaryImages/WithMapillaryImages";
import WithOpenStreetCamImages from "../../HOCs/WithOpenStreetCamImages/WithOpenStreetCamImages";
import WithSearch from "../../HOCs/WithSearch/WithSearch";
import WithTaskCenterPoint from "../../HOCs/WithTaskCenterPoint/WithTaskCenterPoint";
import WithVisibleLayer from "../../HOCs/WithVisibleLayer/WithVisibleLayer";
import MapillaryViewer from "../../MapillaryViewer/MapillaryViewer";
import OpenStreetCamViewer from "../../OpenStreetCamViewer/OpenStreetCamViewer";
import messages from "./Messages";
import {
animateFeatures,
getClickPolygon,
isClickOnMarker,
orderedFeatureLayers,
} from "./helperFunctions";
import "./TaskMap.scss";
import bbox from "@turf/bbox";
import { toLatLngBounds } from "../../../services/MapBounds/MapBounds";
import MapControlsDrawer from "../../TaskClusterMap/MapControlsDrawer";
const shortcutGroup = "layers";
/**
* TaskMap renders a map (and controls) appropriate for the given task,
* including the various map-related features and configuration options set on
* the task and its parent challenge.
*
* @author [Neil Rotstan](https://github.com/nrotstan)
*/
export const TaskMapContent = (props) => {
const { workspaceContext, setWorkspaceContext } = props;
const map = useMap();
const [showTaskFeatures, setShowTaskFeatures] = useState(true);
const [osmData, setOsmData] = useState(null);
const [showOSMData, setShowOSMData] = useState(false);
const [showOSMElements, setShowOSMElements] = useState({
nodes: true,
ways: true,
areas: true,
});
const [osmDataLoading, setOsmDataLoading] = useState(false);
const [mapillaryViewerImage, setMapillaryViewerImage] = useState(null);
const [openStreetCamViewerImage, setOpenStreetCamViewerImage] = useState(null);
const [directionalityIndicators, setDirectionalityIndicators] = useState({});
const [showMapControlsDrawer, setShowMapControlsDrawer] = useState(true);
useEffect(() => {
if (workspaceContext?.taskMapBounds && workspaceContext?.taskPropertyClicked) {
const isTaskInBundle =
props.taskBundle?.tasks?.some((t) => t.id === workspaceContext.taskMapTask?.id) ||
workspaceContext.taskMapTask?.id === props.task?.id;
if (isTaskInBundle) {
map.setView(workspaceContext.taskMapBounds.getCenter(), workspaceContext.taskMapZoom);
// Clear the flag after handling the property click
if (setWorkspaceContext) {
setWorkspaceContext({
taskPropertyClicked: false,
});
}
}
}
}, [workspaceContext?.taskPropertyClicked]);
const taskFeatures = () => {
if ((props.taskBundle?.tasks?.length ?? 0) > 0) {
return featureCollection(
_flatten(_compact(_map(props.taskBundle.tasks, (task) => task?.geometries?.features))),
).features;
}
// If current OSM data is available, show the feature's current OSM tags
// instead of those bundled with the GeoJSON. We preserve any simplestyle
// properties, allowing display colors and what not to be customized
if ((props.osmElements?.size ?? 0) > 0) {
return AsMappableTask(props.task).featuresWithTags(
props.task?.geometries?.features,
props.osmElements,
true,
supportedSimplestyles,
);
}
return props.task?.geometries?.features;
};
const features = taskFeatures();
const animator = new MapAnimator();
useMapEvents({
moveend: () => {
const bounds = map.getBounds();
const zoom = map.getZoom();
props.setTaskMapBounds(props.task.id, bounds, zoom, false);
if (props.setWorkspaceContext) {
props.setWorkspaceContext({
taskMapTask: props.task,
taskMapBounds: bounds,
taskMapZoom: zoom,
});
}
},
});
/** Process keyboard shortcuts for the layers */
const handleKeyboardShortcuts = (event) => {
const layerShortcuts = props.keyboardShortcutGroups[shortcutGroup];
if (
_isEmpty(layerShortcuts) ||
props.textInputActive(event) ||
event.metaKey ||
event.altKey ||
event.ctrlKey
) {
return;
}
const actions = {
[layerShortcuts.layerOSMData.key]: toggleOSMDataVisibility,
[layerShortcuts.layerTaskFeatures.key]: toggleTaskFeatureVisibility,
[layerShortcuts.layerMapillary.key]: toggleMapillaryVisibility,
};
const action = actions[event.key];
if (action) action();
};
const popupLayerSelectionList = (layers, latlng) => {
const contentElement = document.createElement("div");
contentElement.style.maxHeight = "300px";
ReactDOM.render(
<div className="mr-text-base mr-px-4 mr-links-blue-light">
<h3>{props.intl.formatMessage(messages.layerSelectionHeader)}</h3>
<ol>
{layers.map(([description, layerInfo], index) => (
<IntlProvider
key={`${description}-${index}`}
locale={props.intl.locale}
messages={props.intl.messages}
onError={() => {}} // Suppress errors in the console
textComponent="span"
>
<PropertyList
header={description}
featureProperties={_omit(layerInfo?.geometry?.properties, ["id", "type"])}
/>
</IntlProvider>
))}
</ol>
</div>,
contentElement,
);
L.popup({
closeOnEscapeKey: false, // Otherwise our links won't get a onMouseLeave event
})
.setLatLng(latlng)
.setContent(contentElement)
.openOn(map);
};
const handleMapClick = (e) => {
const clickBounds = getClickPolygon(e, map);
const candidateLayers = new Map();
map.eachLayer((layer) => {
if (!_isEmpty(layer._layers)) {
// multiple features in a layer could match. Detect them and then
// put them into an intuitive order
const intraLayerMatches = [];
for (const featureLayer of Object.values(layer._layers)) {
if (featureLayer.toGeoJSON) {
const featureGeojson = featureLayer.toGeoJSON();
// Look for an overlap between the click and the feature. However, since marker
// layers are represented by an icon (which could extend far beyond the feature
// plus our usual pixel margin), check for a click on the marker itself as well
if (
(featureLayer.getIcon && isClickOnMarker(clickBounds, featureLayer, map)) ||
!booleanDisjoint(clickBounds, featureGeojson)
) {
const featureId = AsIdentifiableFeature(featureGeojson).normalizedTypeAndId();
const featureName = featureGeojson?.properties?.name;
let layerDescription =
(featureLayer.options.mrLayerLabel || "") + (featureId ? `: ${featureId}` : "");
if (!layerDescription) {
// worst case, fall back to a layer id (ours, preferably, or leaflet's)
layerDescription = `Layer ${featureLayer.mrLayerId || featureLayer._leaflet_id}`;
}
const layerLabel = featureName ? (
<React.Fragment>
<div>{layerDescription}</div>
<div className="mr-text-grey-light mr-text-xs">{featureName}</div>
</React.Fragment>
) : (
layerDescription
);
intraLayerMatches.push({
mrLayerId: featureLayer.options.mrLayerId,
description: layerDescription,
label: layerLabel,
geometry: featureGeojson,
layer: featureLayer,
});
}
}
}
if (intraLayerMatches.length > 0) {
for (const match of orderedFeatureLayers(intraLayerMatches)) {
candidateLayers.set(match.description, match);
}
}
}
});
if (candidateLayers.size === 1) {
candidateLayers.values().next().value.layer.fire("mr-external-interaction", {
map: map,
latlng: e.latlng,
});
} else if (candidateLayers.size > 1) {
let layers = [...candidateLayers.entries()];
if (props.overlayOrder && props.overlayOrder.length > 0) {
layers = _sortBy(layers, (layerEntry) => {
const position = props.overlayOrder.indexOf(layerEntry[1].mrLayerId);
return position === -1 ? Number.MAX_SAFE_INTEGER : position;
});
}
popupLayerSelectionList(layers, e.latlng);
}
};
/**
* Invoked by LayerToggle when the user wishes to toggle visibility of
* task features on or off.
*/
const toggleTaskFeatureVisibility = () => {
setShowTaskFeatures((prevState) => !prevState);
};
const fetchOSMData = async () => {
try {
if (showOSMData) {
const bounds = map.getBounds()?.toBBoxString();
if (!bounds) {
throw new Error("Invalid map bounds");
}
const xmlData = await props.fetchOSMData(bounds);
setOsmData(xmlData);
setShowOSMData(true);
} else {
setOsmData(null);
setShowOSMData(false);
}
} catch (error) {
console.error("Error handling OSM data:", error);
setOsmData(null);
setShowOSMData(false);
} finally {
setOsmDataLoading(false);
}
};
/**
* Invoked by LayerToggle when the user wishes to toggle visibility of
* OSM data on or off.
*/
const toggleOSMDataVisibility = async () => {
// Prevent multiple requests while loading
if (osmDataLoading) {
return;
}
const loadOSMData = !showOSMData;
setOsmDataLoading(true);
try {
if (loadOSMData) {
const bounds = map.getBounds()?.toBBoxString();
if (!bounds) {
throw new Error("Invalid map bounds");
}
const xmlData = await props.fetchOSMData(bounds);
setOsmData(xmlData);
setShowOSMData(true);
} else {
setOsmData(null);
setShowOSMData(false);
}
} catch (error) {
console.error("Error handling OSM data:", error);
setOsmData(null);
setShowOSMData(false);
} finally {
setOsmDataLoading(false);
}
};
const toggleOSMElements = (element) => {
const newShowOSMElements = _clone(showOSMElements);
newShowOSMElements[element] = !showOSMElements[element];
setShowOSMElements(newShowOSMElements);
};
/**
* Invoked by LayerToggle when the user wishes to toggle visibility of
* Mapillary markers on or off.
*/
const toggleMapillaryVisibility = async () => {
const isVirtual = Number.isFinite(props.virtualChallengeId);
const challengeId = isVirtual ? props.virtualChallengeId : props.challenge.id;
// If enabling layer, fetch fresh data. This allows users to toggle the
// layer off and on to refresh the data, e.g. if they have moved the map
// and wish to expand coverage of mapillary imagery
if (!props.showMapillaryLayer) {
props.setShowMapillaryLayer(challengeId, isVirtual, true);
try {
await props.fetchMapillaryImagery(map.getBounds(), props.task);
} catch (error) {
console.error("Error fetching Mapillary imagery:", error);
}
} else {
props.setShowMapillaryLayer(challengeId, isVirtual, !props.showMapillaryLayer);
}
};
/**
* Reloads the task data with mapillary image info requested if needed
*/
const loadMapillaryIfNeeded = async () => {
// If we're supposed to show mapillary images but don't have them for
// this task, go ahead and fetch them
if (props.task && props.showMapillaryLayer) {
if (
props.mapillaryTaskId !== props.taskId ||
(!props.mapillaryImages && !props.mapillaryLoading)
) {
try {
await props.fetchMapillaryImagery(map.getBounds(), props.task);
} catch (error) {
console.error("Error loading Mapillary imagery:", error);
}
}
}
};
/**
* Invoked by LayerToggle when the user wishes to toggle visibility of
* OpenStreetCam markers on or off.
*/
const toggleOpenStreetCamVisibility = async () => {
const isVirtual = Number.isFinite(props.virtualChallengeId);
const challengeId = isVirtual ? props.virtualChallengeId : props.challenge.id;
// If enabling layer, fetch fresh data. This allows users to toggle the
// layer off and on to refresh the data, e.g. if they have moved the map
// and wish to expand coverage of OpenStreetCam imagery
if (!props.showOpenStreetCamLayer) {
props.setShowOpenStreetCamLayer(challengeId, isVirtual, true);
try {
await props.fetchOpenStreetCamImagery(map.getBounds(), props.task);
} catch (error) {
console.error("Error fetching OpenStreetCam imagery:", error);
}
} else {
props.setShowOpenStreetCamLayer(challengeId, isVirtual, !props.showOpenStreetCamLayer);
}
};
/**
* Reloads the task data with OpenStreetCam image info requested if needed
*/
const loadOpenStreetCamIfNeeded = async () => {
// If we're supposed to show openStreetCam images but don't have them for
// this task, go ahead and fetch them
if (props.task && props.showOpenStreetCamLayer) {
if (
props.openStreetCamTaskId !== props.taskId ||
(!props.openStreetCamImages && !props.openStreetCamLoading)
) {
try {
await props.fetchOpenStreetCamImagery(map.getBounds(), props.task);
} catch (error) {
console.error("Error loading OpenStreetCam imagery:", error);
}
}
}
};
useEffect(() => {
props.activateKeyboardShortcutGroup(
_pick(props.keyboardShortcutGroups, shortcutGroup),
handleKeyboardShortcuts,
);
loadMapillaryIfNeeded();
loadOpenStreetCamIfNeeded();
generateDirectionalityMarkers();
animator.setAnimationFunction(animateFeatures);
map.on("click", handleMapClick);
return () => {
props.deactivateKeyboardShortcutGroup(shortcutGroup, handleKeyboardShortcuts);
animator.reset();
map.off("click", handleMapClick);
};
}, [props.task.id]);
useEffect(() => {
setOsmData(null);
}, [props.task.id, props.task.geometries]);
useEffect(() => {
loadMapillaryIfNeeded();
loadOpenStreetCamIfNeeded();
animator.setAnimationFunction(animateFeatures);
if (showOSMData && !osmData) {
fetchOSMData();
}
}, [showOSMData, osmData]);
useEffect(() => {
if (features.length !== 0) {
const layerGroup = L.featureGroup(features.map((feature) => L.geoJSON(feature)));
map.fitBounds(layerGroup.getBounds().pad(0.2));
}
setShowOSMData(false);
setOsmData(null);
setOsmDataLoading(false);
generateDirectionalityMarkers();
map.closePopup();
}, [props.taskBundle, props.taskId]);
const generateDirectionalityMarkers = () => {
const markers = [];
const allFeatures = features;
for (const [featureIndex, feature] of allFeatures.entries()) {
if (!feature.properties || !feature.properties.oneway) {
continue;
}
const styles = AsSimpleStyleableFeature(
feature,
props.challenge?.taskStyles,
).getFinalLayerStyles();
const coords = coordAll(feature);
if (["yes", "true", "1"].indexOf(feature.properties.oneway) !== -1) {
for (let i = 0; i < coords.length - 1; i++) {
markers.push(
<DirectionalIndicationMarker
key={`directional-marker-${props.task.id}-${featureIndex}-${i}`}
betweenPoints={[point(coords[i]), point(coords[i + 1])]}
atMidpoint
styles={styles}
/>,
);
}
} else if (["-1", "reverse"].indexOf(feature.properties.oneway) !== -1) {
for (let i = coords.length - 1; i > 0; i--) {
markers.push(
<DirectionalIndicationMarker
key={`directional-marker-${props.task.id}-${featureIndex}-${i}`}
betweenPoints={[point(coords[i]), point(coords[i - 1])]}
atMidpoint
styles={styles}
/>,
);
}
}
}
setDirectionalityIndicators({
id: "directionality-indicators",
component: <LayerGroup key="directionality-indicators">{markers}</LayerGroup>,
});
};
const mapillaryImageMarkers = () => {
return {
id: "mapillary",
component: (
<ImageMarkerLayer
key="mapillary"
mrLayerId="mapillary"
mrLayerLabel="Mapillary"
images={props.mapillaryImages}
markerColor="#39AF64"
imageClicked={(imageKey) => setMapillaryViewerImage(imageKey)}
imageAlt="Mapillary"
/>
),
};
};
const openStreetCamImageMarkers = () => ({
id: "openstreetcam",
component: (
<ImageMarkerLayer
key="openstreetcam"
mrLayerId="openstreetcam"
mrLayerLabel="OpenStreetCam"
images={props.openStreetCamImages}
markerColor="#C851E0"
imageClicked={(imageKey) => setOpenStreetCamViewerImage(imageKey)}
imageAlt="OpenStreetCam"
/>
),
});
const applyStyling = (taskFeatures) => {
// If the challenge has conditional styles, apply those
const conditionalStyles = props.challenge?.taskStyles;
if (conditionalStyles) {
return _map(taskFeatures, (feature) => AsSimpleStyleableFeature(feature, conditionalStyles));
}
// Otherwise just give back the features as-is
return taskFeatures;
};
const sortOverlayLayers = (layers) => {
let overlayOrder = props.getUserAppSetting(props.user, "mapOverlayOrder");
if (_isEmpty(overlayOrder)) {
overlayOrder = DEFAULT_OVERLAY_ORDER;
}
// Sort the overlays according to the user's preferences. We then reverse
// that order because the layer rendered on the map last will be on top
if (overlayOrder && overlayOrder.length > 0) {
return _sortBy(layers, (layer) => {
const position = overlayOrder.indexOf(layer.id);
return position === -1 ? Number.MAX_SAFE_INTEGER : position;
}).reverse();
}
return layers;
};
const maxZoom = props.task?.parent?.maxZoom ?? MAX_ZOOM;
const renderMapillaryViewer = () => {
return (
<MapillaryViewer
key={Date.now()}
initialImageKey={mapillaryViewerImage}
onClose={() => setMapillaryViewerImage(null)}
/>
);
};
const taskFeatureLayer = useMemo(() => {
return {
id: "task-features",
component: (
<TaskFeatureLayer
key="task-features"
mrLayerId="task-features"
features={applyStyling(features)}
animator={animator}
externalInteractive
/>
),
};
}, [props.taskBundle, props.taskId]);
const overlayLayers = () => {
let layers = buildLayerSources(
props.visibleOverlays,
props.user?.settings?.customBasemaps,
(layerId, index, layerSource) => ({
id: layerId,
component: <SourcedTileLayer key={layerId} source={layerSource} mrLayerId={layerId} />,
}),
);
if (showTaskFeatures) {
layers.push(taskFeatureLayer);
}
if (props.showMapillaryLayer) {
layers.push(mapillaryImageMarkers());
}
if (props.showOpenStreetCamLayer) {
layers.push(openStreetCamImageMarkers());
}
if (showOSMData && osmData) {
layers.push({
id: "osm-data",
component: (
<OSMDataLayer
key="osm-data"
mrLayerId="osm-data"
xmlData={osmData}
zoom={map.getZoom()}
showOSMElements={showOSMElements}
animator={animator}
externalInteractive
/>
),
});
}
if (showTaskFeatures && !_isEmpty(directionalityIndicators)) {
layers.push(directionalityIndicators);
}
return sortOverlayLayers(layers);
};
if (!props.task || !_isObject(props.task.parent)) {
return <BusySpinner />;
}
const taskCenter = AsMappableTask(props.task).calculateCenterPoint();
return (
<div
className={classNames("task-map task", {
"full-screen-map": props.isMobile,
})}
>
<MapControlsDrawer
isOpen={showMapControlsDrawer}
handleToggleDrawer={() => setShowMapControlsDrawer(!showMapControlsDrawer)}
showTaskFeatures={showTaskFeatures}
toggleTaskFeatures={toggleTaskFeatureVisibility}
showOSMData={showOSMData}
toggleOSMData={toggleOSMDataVisibility}
showOSMElements={showOSMElements}
toggleOSMElements={toggleOSMElements}
osmDataLoading={osmDataLoading}
toggleMapillary={props.isMapillaryEnabled() ? toggleMapillaryVisibility : undefined}
showMapillary={props.showMapillaryLayer}
mapillaryCount={props.mapillaryImages?.length ?? 0}
toggleOpenStreetCam={
props.isOpenStreetCamEnabled() ? toggleOpenStreetCamVisibility : undefined
}
showOpenStreetCam={props.showOpenStreetCamLayer}
openStreetCamCount={props.openStreetCamImages?.length ?? 0}
overlayOrder={props.getUserAppSetting(props.user, "mapOverlayOrder")}
centerBounds={
props.taskBundle
? toLatLngBounds(
bbox({
type: "FeatureCollection",
features: _map(features, (feature) => ({
type: "Feature",
geometry: {
type: "Point",
coordinates: [
feature.geometry.coordinates[0],
feature.geometry.coordinates[1],
],
},
})),
}),
)
: null
}
taskCenter={taskCenter}
fitBoundsControl
showFitWorld
{...props}
/>
<SourcedTileLayer maxZoom={maxZoom} {...props} />
{overlayLayers().map((layer, index) => (
<Pane
key={`pane-${index}`}
name={`pane-${index}`}
style={{ zIndex: 10 + index }}
className="custom-pane"
>
{layer.component}
</Pane>
))}
{mapillaryViewerImage && renderMapillaryViewer()}
{openStreetCamViewerImage && (
<OpenStreetCamViewer
key={Date.now()}
images={props.openStreetCamImages}
initialImageKey={openStreetCamViewerImage}
onClose={() => setOpenStreetCamViewerImage(null)}
/>
)}
</div>
);
};
const TaskMap = (props) => {
const ResizeMap = () => {
const map = useMap();
useEffect(() => {
map.invalidateSize();
}, [map]);
return null;
};
return (
<div
className={classNames("task-map task", {
"full-screen-map": props.isMobile,
})}
>
<MapContainer
taskBundle={props.taskBundle}
center={props.centerPoint}
zoomControl={false}
zoom={DEFAULT_ZOOM}
minZoom={2}
maxZoom={MAX_ZOOM}
attributionControl={false}
maxBounds={[
[-90, -180],
[90, 180],
]}
>
<ResizeMap />
<AttributionControl position="bottomleft" prefix={false} />
<TaskMapContent {...props} />
</MapContainer>
</div>
);
};
TaskMap.propTypes = {
taskBundle: PropTypes.object,
/**
* The desired centerpoint of the map in (Lat, Lng).
* @see See WithTaskCenterpoint HOC
*/
centerPoint: PropTypes.object.isRequired,
task: PropTypes.object,
setTaskMapBounds: PropTypes.func.isRequired,
};
export default WithSearch(
WithMapillaryImages(
WithOpenStreetCamImages(
WithTaskCenterPoint(
WithVisibleLayer(WithIntersectingOverlays(WithKeyboardShortcuts(TaskMap), "task")),
),
),
),
"task",
);