-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathredux-map.jsx
1293 lines (1114 loc) · 38.6 KB
/
redux-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
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
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint-disable react/prop-types */
import React, { useRef, useEffect, useState, useCallback } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import wellknown from 'wellknown';
import proj4 from 'proj4';
import mapboxgl from 'mapbox-gl';
import MapboxGeocoder from '@mapbox/mapbox-gl-geocoder';
import MapboxDraw from '@mapbox/mapbox-gl-draw';
const MAPBOX_TOKEN = typeof process !== 'undefined'
// eslint-disable-next-line no-undef
? process.env.REACT_APP_MAPBOX_API_KEY
: import.meta.env.VITE_MAPBOX_API_KEY || import.meta.env.VITE_API_MAPBOX_TOKEN;
import area from '@turf/area';
import bbox from '@turf/bbox';
import union from '@turf/union';
import centroid from '@turf/centroid';
import { polygon, featureCollection } from '@turf/helpers';
import * as shapefile from 'shapefile';
import { geocodeReverse, coordinatesGeocoder } from './helpers';
import fullscreenIcon from './fullscreen.png';
import polygonIcon from './polygon.png';
import freehandIcon from './freehand.png';
import trashcanIcon from './trashcan.png';
import styles from './map.module.scss';
import './mapbox-gl.css';
import './mapbox-gl-draw.css';
import './mapbox-gl-geocoder.css';
import './psa-mapbox.scss';
const turf = {
area,
polygon,
bbox,
union,
featureCollection,
centroid,
};
const conus = [
[-124.731422, 24.743319], // Southwest coordinates
[-66.969849, 49.345786], // Northeast coordinates
];
const getBounds = (bounds) => {
if (bounds === 'conus') return conus;
return bounds;
};
const elevations = {};
let fpolygon = [[]];
const Help = ({
hasMarkerMovable, hasFreehand, hasFullscreen, hasImport, otherHelp,
}) => (
<dialog id="MapHelp">
<button
type="button"
onClick={(event) => {
event.target.closest('dialog').close();
}}
>
X
</button>
<p><strong>Controls</strong></p>
{
hasMarkerMovable
? (
<p>
You can move the marker by dragging it.
</p>
)
: null
}
{
hasFullscreen
? (
<p>
For a larger map after the location is selected, click the full screen icon:
<img className="icon" alt="fullscreen" src={fullscreenIcon} />
</p>
)
: null
}
<p>
You can use the polygon tool on the right side of the map to outline the site area and estimate its acreage:
<img className="icon" alt="polygon" src={polygonIcon} />
<br />
To create the boundary, click on each point that defines your field on the map.
<br />
Double-click the final point to close the polygon.
</p>
{
hasFreehand
? (
<p>
You can also use the freehand tool to outline the site area and estimate its acreage:
<img className="icon" alt="freehand" src={freehandIcon} />
<br />
To create the boundary, click on the edge of your field and drag the mouse around the perimeter.
<br />
Release the mouse button to close the polygon.
</p>
)
: null
}
{
hasImport
? (
<p>
If you already have a shape file with your field boundaries, you can import it by clicking the
<strong>SHP</strong>
button.
</p>
)
: null
}
<p>
To delete and re-draw polygons, select the polygon, then click the trash can icon under the polygon tool:
<img className="icon" alt="trashcan" src={trashcanIcon} />
</p>
{otherHelp}
</dialog>
);
const ReduxMap = ({
getter,
setter,
setMap = () => {},
setProperties = () => {},
initWidth,
initHeight,
initFeatures = [],
initAddress = 'Search for your address ...',
initLat = 0,
initLon = 0,
initStartZoom,
hasClear = false,
hasSearchBar = false,
hasMarker = false,
hasNavigation = false,
hasCoordBar = false,
hasFreehand = false,
hasDrawing = false,
hasGeolocate = false,
hasFullScreen = false,
hasMarkerMovable = false,
hasImport = false,
hasElevation = false,
hasHelp = false,
scrollZoom = true,
dragRotate = true,
dragPan = true,
keyboard = true,
doubleClickZoom = false,
touchZoomRotate = true,
markerOptions = {},
autoFocus = false,
layer = 'mapbox://styles/mapbox/satellite-streets-v12',
initBounds,
fitMapToPolygons = false,
fitBounds = false,
defaultZoom = 15,
showZoom = false,
otherHelp,
}) => {
const mapRef = useRef({});
const timerRef = useRef(null);
const useSafeSelector = (fallbackValue, parm, getter, setter) => {
const dispatch = useDispatch();
const selectedValue = useSelector(getter?.[parm] || (() => fallbackValue));
const [localState, setLocalState] = useState(selectedValue);
useEffect(() => {
if (parm === 'features' && JSON.stringify(fallbackValue) === JSON.stringify(selectedValue)) {
return;
} else if (parm === 'address' && !fallbackValue) {
setLocalState({});
} else if (fallbackValue && !getter?.[parm]) {
setLocalState(fallbackValue);
}
}, [fallbackValue]);
const setLocalStateWithDispatch = useCallback((newValue) => {
mapRef.current = { ...mapRef.current, [parm]: newValue };
setLocalState(newValue);
if (setter) {
clearTimeout(timerRef?.current);
timerRef.current = setTimeout(() => {
dispatch(setter((currentMap) => ({
...currentMap,
...mapRef.current,
})));
}, 50);
}
}, [dispatch, setter, parm]);
return [localState, setLocalStateWithDispatch];
}; // useSafeSelector
let newPolygon;
const boundsPadding = hasSearchBar ? 50 : 20;
const [lat, setLat] = useSafeSelector(initLat, 'lat', getter, setter);
const [lon, setLon] = useSafeSelector(initLon, 'lon', getter, setter);
const [polygonArea, setPolygonArea] = useSafeSelector(0, 'area', getter, setter);
const [elevation, setElevation] = useSafeSelector(0, 'elevation', getter, setter);
// const [address, setAddress] = useSafeSelector({
// address: '',
// fullAddress: '',
// city: '',
// county: '',
// state: '',
// stateCode: '',
// zipCode: '',
// }, 'address', getter, setter);
const [address, setAddress] = useSafeSelector(null, 'address', getter, setter);
const [features, setFeatures] = useSafeSelector(initFeatures, 'features', getter, setter);
const [zoom, setZoom] = useSafeSelector(initStartZoom ?? defaultZoom, 'zoom', getter, setter);
const [bounds, setBounds] = useSafeSelector(initBounds, 'bounds', getter, setter);
useEffect(() => {
setProperties({
lat,
lon,
elevation,
zoom,
area: polygonArea,
bounds,
address: address ?? {},
features,
});
}, [lat, lon, elevation, zoom, polygonArea, bounds, address, features]);
const [cursorLoc, setCursorLoc] = useState({ longitude: undefined, latitude: undefined });
const [isDrawActive, setIsDrawActive] = useState(false);
const [searchBox, setSearchBox] = useState();
const [dragging, setDragging] = useState(false);
const map = useRef();
const mapContainer = useRef();
const drawerRef = useRef();
const markerRef = useRef();
const popupRef = useRef();
const geocoderRef = useRef();
const cursorRef = useRef();
const inFreehand = () => mapContainer.current?.querySelector('#freehand')?.classList?.contains('active');
const acreDiv = 4046.856422;
const popup = (plat, plon) => (`
<div class="popup">
<div>Click to drag</div>
${plat.toFixed(4)}, ${plon.toFixed(4)}
</div>
`);
const calcArea = (f) => {
const newFeatures = JSON.parse(JSON.stringify(f));
let totalArea = 0;
if (newFeatures.length === 1) {
totalArea = turf.area(newFeatures[0]) / acreDiv;
} else {
const polygons = newFeatures.map((feature) => {
feature.geometry.coordinates[0].push(feature.geometry.coordinates[0][0]); // may not be self-closing
return turf.polygon(feature.geometry.coordinates);
});
if (polygons.length) {
const punion = turf.union(turf.featureCollection(polygons));
totalArea = turf.area(punion) / acreDiv;
}
}
return totalArea;
}; // calcArea
const updateFeatures = (newLat, newLon) => {
const newFeatures = [];
const { sources } = map.current.getStyle();
drawerRef?.current?.deleteAll?.();
Object.keys(sources).forEach((sourceName) => {
const source = map.current.getSource(sourceName);
if (source.type === 'geojson') {
const data = { ...source._data };
const f = data.features || [data];
newFeatures.push(...f.filter((feature) => /Polygon/.test(feature.geometry.type)));
}
});
setFeatures(newFeatures);
setPolygonArea(calcArea(newFeatures));
if (newLat) {
setLat(newLat);
setLon(newLon);
}
}; // updateFeatures
if (searchBox && autoFocus) {
searchBox.focus();
}
// useEffect definitions
/**
* Handles click and mousemove events for the Mapbox Geocoder searchbox.
*
* This effect attaches event listeners to the Mapbox Geocoder container (`.mapboxgl-ctrl-geocoder`).
* When a user clicks within the last 20 pixels of the container's width, it triggers a reset of various states
* including latitude, longitude, polygon area, and address details. The mousemove event toggles a CSS class
* if the cursor is hovering near the right edge of the container.
*
* @effect
* Attaches the `click` and `mousemove` event listeners to the Geocoder container when the component mounts,
* and removes them when the component unmounts or the `map` dependency changes.
*/
useEffect(() => { // map.current
const handleClick = (event) => {
const target = event.currentTarget;
const rect = target.getBoundingClientRect();
const clickX = event.clientX - rect.left;
if (hasClear && rect.width - clickX <= 20) {
setLat(0);
setLon(0);
setPolygonArea(0);
setAddress({
fullAddress: '',
city: '',
county: '',
state: '',
stateCode: '',
zipCode: '',
});
setFeatures([]);
setBounds('conus');
}
};
const handleMousemove = (event) => {
const target = event.currentTarget;
const rect = target.getBoundingClientRect();
const clickX = event.clientX - rect.left;
target.classList.toggle('clearHovered', rect.width - clickX <= 20);
};
const geocoderContainer = document.querySelector('.mapboxgl-ctrl-geocoder');
geocoderContainer?.addEventListener('click', handleClick);
geocoderContainer?.addEventListener('mousemove', handleMousemove);
return () => {
geocoderContainer?.removeEventListener('click', handleClick);
geocoderContainer?.removeEventListener('mousemove', handleMousemove);
};
}, [map.current]);
useEffect(() => { // markerRef.current
const handleMarkerEnter = (event) => {
if (event.buttons === 0) {
markerRef.current.togglePopup();
}
};
const handleMarkerLeave = (event) => {
if (event.buttons === 0) {
markerRef.current.getPopup().remove();
}
};
if (hasMarkerMovable && markerRef.current) {
markerRef.current.getElement().addEventListener('mouseenter', handleMarkerEnter);
markerRef.current.getElement().addEventListener('mouseleave', handleMarkerLeave);
// update Popup content while marker is being dragged
markerRef.current.on('drag', () => {
markerRef.current.getPopup().setHTML(popup(markerRef.current.getLngLat().lat, markerRef.current.getLngLat().lng));
});
markerRef.current.on('dragend', (e) => {
const lngLat = e.target.getLngLat();
setLat(lngLat.lat);
setLon(lngLat.lng);
map.current.setCenter(lngLat);
});
}
return () => {
markerRef?.current?.getElement().removeEventListener('mouseenter', handleMarkerEnter);
markerRef?.current?.getElement().removeEventListener('mouseleave', handleMarkerLeave);
};
}, [markerRef.current]);
const isLikelyWGS84 = (coords) => {
if (!Array.isArray(coords) || coords.length === 0) return false;
const sample = Array.isArray(coords[0]) ? coords[0][0] : coords; // Handle nested arrays
const [x, y] = sample;
return y >= -90 && y <= 90 && x >= -180 && x <= 180;
};
const convertToWGS84 = (coords, fromCRS) => {
if (!fromCRS || fromCRS === 'EPSG:4326') return coords;
const projStrings = {
'EPSG:3857': 'EPSG:4326', // Web Mercator to WGS84
};
if (fromCRS.startsWith('EPSG:269')) {
const zone = fromCRS.slice(-2);
projStrings[fromCRS] = `+proj=utm +zone=${zone} +datum=NAD83 +units=m +no_defs`;
}
return proj4(projStrings[fromCRS], 'EPSG:4326', coords);
};
const parsePRJ = (prjText) => {
console.log('📄 .prj File Contents:\n', prjText);
// Match UTM zone from PROJCS["NAD_1983_UTM_Zone_XXN"]
const match = prjText.match(/NAD_1983_UTM_Zone_(\d+)N/);
if (match) {
const zone = parseInt(match[1], 10);
const epsgCode = `EPSG:269${zone}`; // NAD83 UTM Zone
console.log(`✅ Detected UTM Zone: ${zone} (${epsgCode})`);
return epsgCode;
}
console.warn('⚠️ Could not determine projection from .prj file.');
return null;
};
// ________________________________________________________________________________
/**
* Loads and processes a shapefile uploaded by the user.
*
* This function reads a shapefile from an uploaded file using the File API,
* processes the shapefile's geometry to calculate the centroid, bounding box,
* and area. The processed data is then used to update the map's features, bounds,
* polygon area, and the latitude/longitude of the map's center.
*/
const loadShapeFile = (event) => {
const files = event.target.files;
let shpFile = null, prjFile = null;
for (let file of files) {
if (file.name.endsWith('.shp')) shpFile = file;
if (file.name.endsWith('.prj')) prjFile = file;
}
if (!shpFile) {
alert('Please upload a .shp file.');
return;
}
const reader = new FileReader();
reader.onload = async () => {
const arrayBuffer = reader.result;
const layers = [];
let projection = null;
if (prjFile) {
try {
const prjText = await prjFile.text();
projection = parsePRJ(prjText);
console.log('📌 Detected Projection:', projection);
} catch (error) {
console.warn(`⚠️ Could not read .prj file. Defaulting to automatic detection. Error: ${error.message}`);
}
}
shapefile
.open(arrayBuffer)
.then((source) => {
source.read()
.then(function log(result) {
if (result.done) return;
const { geometry } = result.value;
// ✅ Step 1: If coordinates are already WGS84, no transformation is needed
if (isLikelyWGS84(geometry.coordinates)) {
console.log('✅ Data is already in WGS84, skipping projection.');
} else {
// ⚠️ Step 2: Use `.prj` file if available, otherwise ask user
if (!projection) {
const userZone = prompt('⚠️ No .prj file detected.\n\nPlease enter the correct UTM zone\n(e.g., 10 for Zone 10, 11 for Zone 11):');
if (userZone && userZone.match(/^\d{1,2}$/)) {
projection = `EPSG:269${userZone}`;
console.log(`✅ User selected UTM Zone: ${userZone} (EPSG:${projection})`);
} else {
alert('Invalid UTM zone. Unable to determine CRS.');
return;
}
}
// Convert coordinates to WGS84
if (geometry.type === 'MultiPolygon') {
geometry.coordinates = geometry.coordinates.map((polygon) =>
polygon.map((ring) =>
ring.map((coord) => convertToWGS84(coord, projection))
)
);
} else if (geometry.type === 'Polygon' || geometry.type === 'MultiLineString') {
geometry.coordinates = geometry.coordinates.map((ring) =>
ring.map((coord) => convertToWGS84(coord, projection))
);
} else if (geometry.type === 'LineString' || geometry.type === 'MultiPoint') {
geometry.coordinates = geometry.coordinates.map((coord) => convertToWGS84(coord, projection));
} else if (geometry.type === 'Point') {
geometry.coordinates = convertToWGS84(geometry.coordinates, projection);
}
}
layers.push(result.value);
return source.read().then(log);
})
.catch((error) => {
console.error(error);
})
.finally(() => {
mapContainer.current.scrollIntoView();
const fc = {
type: 'FeatureCollection',
features: layers,
};
const [avgLon, avgLat] = turf.centroid(fc).geometry.coordinates;
setFeatures(layers);
setBounds(turf.bbox(fc));
setPolygonArea(turf.area(fc) / acreDiv);
setLat(avgLat);
setLon(avgLon);
});
})
.catch((error) => {
alert(`Could not process file:\n${error}`);
console.log(error);
});
};
reader.readAsArrayBuffer(shpFile);
};
/// / GEOCODER CONTROL
const Geocoder = new MapboxGeocoder({
placeholder: initAddress,
localGeocoder: coordinatesGeocoder,
marker: false,
accessToken: MAPBOX_TOKEN,
container: map.current,
proximity: 'ip',
trackProximity: true,
countries: 'us',
});
geocoderRef.current = Geocoder;
const deleteFeatures = (gresult) => {
if (gresult && hasDrawing && drawerRef.current) {
drawerRef.current.deleteAll();
setPolygonArea(0);
setFeatures([]);
}
};
// upon marker move, find the address of this new location and set the state
useEffect(() => { // lat, lon
geocodeReverse({
apiKey: MAPBOX_TOKEN,
setterFunc: (addr) => {
setAddress(addr());
const sb = document.querySelector('.mapboxgl-ctrl-geocoder--input');
if (sb) {
sb.value = '';
sb.placeholder = addr().fullAddress;
}
},
longitude: lon,
latitude: lat,
});
if (hasElevation) {
getElevation(lat, lon);
}
if (markerRef.current) {
const lngLat = [lon, lat];
markerRef.current.setLngLat(lngLat).setPopup(popupRef.current);
map.current.setCenter(lngLat);
}
}, [lon, lat]);
useEffect(() => {
if (
drawerRef.current
&& features?.length
) {
try {
drawerRef.current?.deleteAll?.();
if (Array.isArray(features[0])) {
features.forEach((f) => {
drawerRef.current.add({
type: 'FeatureCollection',
f,
});
});
} else {
try {
features.forEach((feature) => {
drawerRef.current.add(feature);
});
} catch {
//
}
}
setPolygonArea(calcArea(features));
} catch {
// only happens when importing shapefile from opening map without setter
}
}
}, [features, drawerRef.current]);
useEffect(() => {
if (bounds && map.current) {
map.current.fitBounds(getBounds(bounds), {
duration: 0,
padding: boundsPadding,
});
}
}, [bounds, map.current]);
useEffect(() => { // map
// initialize map only once
if (!map.current) {
const Map = new mapboxgl.Map({
accessToken: MAPBOX_TOKEN,
container: mapContainer.current,
style: layer,
center: [lon, lat],
zoom,
});
map.current = Map;
const Popup = new mapboxgl.Popup({ offset: 25, closeButton: false }).setHTML(popup(lat, lon));
popupRef.current = Popup;
/// / MARKER CONTROL
const Marker = new mapboxgl.Marker({
draggable: hasMarkerMovable,
color: '#e63946',
scale: 1,
...markerOptions,
}).setLngLat([lon, lat]);
markerRef.current = Marker;
Marker.className = styles.marker;
if (hasMarkerMovable) {
Marker.setPopup(Popup);
}
const simpleSelect = MapboxDraw.modes.simple_select;
const directSelect = MapboxDraw.modes.direct_select;
simpleSelect.dragMove = () => {};
directSelect.dragFeature = () => {};
// DRAWER CONTROL
const Draw = new MapboxDraw({
displayControlsDefault: false,
controls: { polygon: true, trash: true },
modes: {
...MapboxDraw.modes,
simple_select: simpleSelect,
direct_select: directSelect,
},
});
drawerRef.current = Draw;
/// / GEOLOCATE CONTROL
const Geolocate = new mapboxgl.GeolocateControl({ container: map.current });
/// / NAVIGATION CONTROL
const Navigation = new mapboxgl.NavigationControl({
container: map.current,
});
/// / FULLSCREEN CONTROL
const Fullscreen = new mapboxgl.FullscreenControl();
/// / ADD CONTROLS
if (hasFullScreen) map.current.addControl(Fullscreen, 'top-right');
if (hasNavigation) map.current.addControl(Navigation, 'top-right'); // causes warning
if (hasGeolocate) map.current.addControl(Geolocate, 'top-right');
if (hasDrawing) map.current.addControl(Draw, 'top-right');
if (hasSearchBar) map.current.addControl(Geocoder, 'top-left');
if (hasMarker && !isDrawActive) markerRef.current.addTo(map.current);
/// / FUNCTIONS
const handleGeolocate = (e) => {
const lngLat = e.target._userLocationDotMarker._lngLat;
setLat(lngLat.lat);
setLon(lngLat.lng);
setZoom(map.current.getZoom());
setBounds(false);
setPolygonArea(0);
setFeatures([]);
if (hasDrawing && drawerRef.current) {
drawerRef?.current?.deleteAll();
}
}; // handleGeolocate
const handleDrawCreate = (geom) => {
updateFeatures();
if (geom.features.length > 0) {
const coords = turf.centroid(geom.features[0]).geometry.coordinates;
setLat(coords[1]);
setLon(coords[0]);
}
newPolygon = true;
setTimeout(() => {
newPolygon = false;
}, 100);
};
const handleDrawDelete = () => {
setIsDrawActive(false);
setTimeout(updateFeatures, 10);
// updateFeatures();
document.querySelector('.mapbox-gl-draw_trash').style.display = 'none';
};
const showHideTrashcan = (e) => {
const trashButton = document.querySelector('.mapbox-gl-draw_trash');
if (e.features.length > 0) {
trashButton.style.display = 'block';
} else {
trashButton.style.display = 'none';
}
};
/// / EVENTS
Geolocate.on('geolocate', handleGeolocate);
Geolocate.on('error', (error) => {
if (error.code === error.PERMISSION_DENIED) {
alert('Geolocation access denied. Please enable location services.');
}
});
Geocoder.on('result', (e) => {
if (e?.result?.place_name) {
deleteFeatures(e.result);
setLat(e.result.center[1]);
setLon(e.result.center[0]);
setZoom(defaultZoom);
map.current.setZoom(defaultZoom);
setBounds(false);
}
});
if (hasMarkerMovable) {
const dblClick = (e) => {
if (newPolygon) return;
setLat(e.lngLat.lat);
setLon(e.lngLat.lng);
setZoom(defaultZoom);
map.current.setZoom(defaultZoom);
setBounds(false);
e.preventDefault();
}
map.current.on('click', (e) => {
if (lat === 0) dblClick(e);
});
map.current.on('dblclick', dblClick);
}
map.current.on('dragstart', () => setDragging(true));
map.current.on('dragend', () => {
setDragging(false);
setCursorLoc({
latitude: null,
longitude: null,
});
});
map.current.on('mousemove', (e) => {
const lnglat = e.lngLat.wrap();
setCursorLoc({
latitude: lnglat.lat.toFixed(4),
longitude: lnglat.lng.toFixed(4),
});
if (cursorRef.current) {
cursorRef.current.style.left = `${e.originalEvent.pageX - 58}px`;
cursorRef.current.style.top = `${e.originalEvent.pageY - 25}px`;
}
});
map.current.on('load', () => {
const mc = mapContainer.current;
if (!mc) return;
setSearchBox(mc.querySelector('.mapboxgl-ctrl-geocoder--input'));
if (bounds && map.current) {
map.current.fitBounds(getBounds(bounds), {
duration: 0,
padding: boundsPadding,
});
}
if (hasFreehand) {
mc.querySelector('.mapboxgl-ctrl-group:last-of-type button:first-of-type')
?.insertAdjacentHTML(
'afterend',
`
<button
id="freehand"
style="margin-top: 1px solid #ddd;"
title="Freehand tool"
>
<svg id="polygon-tool" class="mapboxgl-ctrl-icon custom-icon" viewBox="0 0 24 24">
<path d="M3 10 L8 3 L15 5 L19 12 L12 20 L5 15 Z" stroke="#000" stroke-width="2" fill="none"></path>
</svg>
</button>
`,
);
const freehand = mc.querySelector('#freehand');
freehand?.addEventListener('click', () => {
freehand.classList.toggle('active');
if (freehand.classList.contains('active')) {
if (hasDrawing) {
document.querySelector('.mapbox-gl-draw_polygon').style.display = 'none';
Draw.changeMode('draw_polygon');
}
map.current.dragPan.disable();
} else {
if (hasDrawing) {
document.querySelector('.mapbox-gl-draw_polygon').style.display = 'block';
Draw.changeMode('simple_select');
}
map.current.dragPan.enable();
}
});
}
if (hasImport) {
mc.querySelector('.mapboxgl-ctrl-group:last-of-type button:last-of-type')
?.insertAdjacentHTML(
'afterend',
`
<button
id="import"
style="font: bold 8pt arial"
title="Import a shape file"
>
SHP
</button>
<input
id="FileUpload"
type="file"
accept=".shp, .prj"
multiple
style="display: none"
/>
`,
);
const markerEl = mc.querySelector('#import');
markerEl.addEventListener('click', () => {
mc.querySelector('#FileUpload').click();
});
const upload = mc.querySelector('#FileUpload');
upload.addEventListener('change', loadShapeFile);
}
if (hasHelp) {
mc.querySelector('.mapboxgl-ctrl-group:last-of-type button:last-of-type')
?.insertAdjacentHTML(
'afterend',
`
<button
title="Help"
onclick="document.querySelector('#MapHelp').showModal();"
>
?
</button>
`,
);
}
if (!scrollZoom) map.current.scrollZoom.disable();
if (!dragRotate) map.current.dragRotate.disable();
if (!dragPan) map.current.dragPan.disable();
if (!keyboard) map.current.keyboard.disable();
if (!doubleClickZoom) map.current.doubleClickZoom.disable();
if (!touchZoomRotate) map.current.touchZoomRotate.disable();
const newLine = () => ({
type: 'FeatureCollection',
features: [
{
type: 'Feature',
geometry: {
type: 'LineString',
coordinates: [],
},
properties: {},
},
],
});
let lineData = newLine();
if (hasFreehand) {
map.current.addSource('line', {
type: 'geojson',
data: lineData,
});
map.current.addLayer({
id: 'line-layer',
type: 'line',
source: 'line',
layout: {
'line-join': 'round',
'line-cap': 'round',
},
paint: {
'line-color': '#fff',
'line-width': 3,
},
});
map.current.on('mousedown', (e) => {
const lnglat = e.lngLat.wrap();
if (inFreehand()) {
lineData = newLine();
lineData.features[0].geometry.coordinates.push([lnglat.lng, lnglat.lat]);
fpolygon = [[lnglat.lng, lnglat.lat]];
}
});
map.current.on('mousemove', (e) => {
const lnglat = e.lngLat.wrap();
if (inFreehand() && fpolygon[0].length) {
lineData.features[0].geometry.coordinates.push([lnglat.lng, lnglat.lat]);
map.current.getSource('line').setData(lineData);
fpolygon.push([lnglat.lng, lnglat.lat]);
}
});
map.current.on('mouseup', () => {
const id = `freehand${+(new Date())}`;
if (inFreehand()) {
const created = fpolygon.length > 1;
if (created) {