-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathMapTemplate.jsx
More file actions
883 lines (805 loc) · 42.3 KB
/
MapTemplate.jsx
File metadata and controls
883 lines (805 loc) · 42.3 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
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
import { Fragment, useEffect, useRef } from 'react';
import { useState } from 'react';
import { useRecoilState, useRecoilValue, useSetRecoilState } from 'recoil';
import { defineCustomElements } from '@mapsindoors/components/dist/components/index.js';
import i18n from 'i18next';
import initI18n from '../../i18n/initialize.js';
import './MapTemplate.scss';
import { mapClickActions } from '../../constants/mapClickActions.js';
import MapWrapper from '../MapWrapper/MapWrapper';
import SplashScreen from '../SplashScreen/SplashScreen';
import VenueSelector from '../VenueSelector/VenueSelector';
import BottomSheet from '../BottomSheet/BottomSheet';
import apiKeyState from '../../atoms/apiKeyState';
import gmApiKeyState from '../../atoms/gmApiKeyState';
import isMapReadyState from '../../atoms/isMapReadyState.js';
import currentLocationState from '../../atoms/currentLocationState';
import tileStyleState from '../../atoms/tileStyleState';
import categoriesState from '../../atoms/categoriesState';
import venuesInSolutionState from '../../atoms/venuesInSolutionState';
import solutionState from '../../atoms/solutionState.js';
import { useAppHistory } from '../../hooks/useAppHistory';
import { useReset } from '../../hooks/useReset.js';
import Sidebar from '../Sidebar/Sidebar';
import useLocationForWayfinding from '../../hooks/useLocationForWayfinding';
import locationIdState from '../../atoms/locationIdState';
import mapboxAccessTokenState from '../../atoms/mapboxAccessTokenState';
import filteredLocationsState from '../../atoms/filteredLocationsState';
import filteredLocationsByExternalIDState from '../../atoms/filteredLocationsByExternalIDState';
import kioskOriginLocationIdState from '../../atoms/kioskOriginLocationIdState.js';
import startZoomLevelState from '../../atoms/startZoomLevelState';
import primaryColorState from '../../atoms/primaryColorState';
import logoState from '../../atoms/logoState';
import gmMapIdState from '../../atoms/gmMapIdState';
import bearingState from '../../atoms/bearingState';
import pitchState from '../../atoms/pitchState';
import mapsIndoorsInstanceState from '../../atoms/mapsIndoorsInstanceState';
import languageState from '../../atoms/languageState.js';
import Notification from '../WebComponentWrappers/Notification/Notification.jsx';
import kioskLocationState from '../../atoms/kioskLocationState';
import timeoutState from '../../atoms/timoutState.js';
import { useInactive } from '../../hooks/useInactive.js';
import qrCodeLinkState from '../../atoms/qrCodeLinkState.js';
import QRCodeDialog from '../QRCodeDialog/QRCodeDialog';
import supportsUrlParametersState from '../../atoms/supportsUrlParametersState';
import useKeyboardState from '../../atoms/useKeyboardState';
import { useIsDesktop } from '../../hooks/useIsDesktop.js';
import miTransitionLevelState from '../../atoms/miTransitionLevelState.js';
import selectedCategoryState from '../../atoms/selectedCategoryState.js';
import LegendDialog from '../LegendDialog/LegendDialog.jsx';
import isLegendDialogVisibleState from '../../atoms/isLegendDialogVisibleState.js';
import searchAllVenuesState from '../../atoms/searchAllVenues.js';
import categoryState from '../../atoms/categoryState.js';
import hideNonMatchesState from '../../atoms/hideNonMatchesState.js';
import appConfigState from '../../atoms/appConfigState.js';
import { useCurrentVenue } from '../../hooks/useCurrentVenue.js';
import showExternalIDsState from '../../atoms/showExternalIDsState.js'
import showRoadNamesState from '../../atoms/showRoadNamesState.js';
import searchExternalLocationsState from '../../atoms/searchExternalLocationsState.js';
import wayfindingLocationState from '../../atoms/wayfindingLocation.js';
import isNullOrUndefined from '../../helpers/isNullOrUndefined.js';
import centerState from '../../atoms/centerState.js';
import PropTypes from 'prop-types';
import { ZoomLevelValues } from '../../constants/zoomLevelValues.js';
import { useOnRouteFinished } from '../../hooks/useOnRouteFinished.js';
import notificationMessageState from '../../atoms/notificationMessageState.js';
import { GeminiProvider } from '../../providers/GeminiProvider';
import ChatButton from '../ChatButton/ChatButton';
import mapTypeState from '../../atoms/mapTypeState.js';
import { mapTypes } from '../../constants/mapTypes.js';
import { useIsKioskContext } from '../../hooks/useIsKioskContext.js';
// Define the Custom Elements from our components package.
defineCustomElements();
MapTemplate.propTypes = {
apiKey: PropTypes.string.isRequired,
gmApiKey: PropTypes.string,
mapboxAccessToken: PropTypes.string,
venue: PropTypes.string,
locationId: PropTypes.string,
primaryColor: PropTypes.string,
logo: PropTypes.string,
appUserRoles: PropTypes.arrayOf(PropTypes.string),
directionsFrom: PropTypes.string,
directionsTo: PropTypes.string,
externalIDs: PropTypes.arrayOf(PropTypes.string),
tileStyle: PropTypes.string,
startZoomLevel: PropTypes.number,
bearing: PropTypes.number,
pitch: PropTypes.number,
gmMapId: PropTypes.string,
useMapProviderModule: PropTypes.bool,
kioskOriginLocationId: PropTypes.string,
language: PropTypes.string,
timeout: PropTypes.number,
useKeyboard: PropTypes.bool,
miTransitionLevel: PropTypes.number,
category: PropTypes.string,
searchAllVenues: PropTypes.bool,
hideNonMatches: PropTypes.bool,
showExternalIDs: PropTypes.bool,
showRoadNames: PropTypes.bool,
searchExternalLocations: PropTypes.bool,
supportsUrlParameters: PropTypes.bool,
center: PropTypes.string,
useAppTitle: PropTypes.bool,
showMapMarkers: PropTypes.bool,
mapboxMapStyle: PropTypes.string,
devicePosition: PropTypes.object
};
/**
*
* @param {Object} props
* @param {string} props.apiKey - MapsIndoors API key or solution alias.
* @param {string} [props.gmApiKey] - Google Maps API key if you want to show a Google Maps map. Can also be set in the MapsIndoors App Config as "gmKey" under "appSettings".
* @param {string} [props.mapboxAccessToken] - Mapbox Access Token if you want to show a Mapbox map. Can also be set in the MapsIndoors App Config "mapboxAccessToken" under "appSettings".
* @param {string} [props.venue] - If you want the map to show a specific Venue, provide the Venue name here.
* @param {string} [props.locationId] - If you want the map to show a specific Location, provide the Location ID here.
* @param {string} [props.primaryColor] - If you want the splash screen to have a custom primary color, provide the value here.
* @param {string} [props.logo] - If you want the splash screen to have a custom logo, provide the image path or address here.
* @param {array} [props.appUserRoles] - If you want the map to behave differently for specific users, set one or more app user roles here.
* @param {string} [props.directionsFrom] - If you want to show directions instantly, provide a MapsIndoors Location ID or the string "USER_POSITION" here to be used as the origin.
* @param {string} [props.directionsTo] - If you want to show directions instantly, provide a MapsIndoors Location ID or the string "USER_POSITION" here to be used as the destination.
* @param {array} [props.externalIDs] - Filter locations shown on the map based on the external IDs.
* @param {string} [props.tileStyle] - Tile style name to change the interface of the map.
* @param {number} [props.startZoomLevel] - The initial zoom level of the map.
* @param {number} [props.bearing] - The bearing of the map as a number. Not recommended for Google Maps with 2D Models.
* @param {number} [props.pitch] - The pitch of the map as a number. Not recommended for Google Maps with 2D Models.
* @param {string} [props.gmMapId] - The Google Maps Map ID associated with a specific map style or feature.
* @param {boolean} [props.useMapProviderModule] - Set to true if the Map Template should take MapsIndoors solution modules into consideration when determining what map type to use.
* @param {string} [props.kioskOriginLocationId] - If running the Map Template as a kiosk (upcoming feature), provide the Location ID that represents the location of the kiosk.
* @param {string} [props.language] - The language to show textual content in. Supported values are "en" for English, "da" for Danish, "de" for German, "fr" for French, "it" for Italian, "es" for Spanish, "nl" for Dutch and "zh" for Chinese. If the prop is not set, the language of the browser will be used (if it is one of the supported languages - otherwise it will default to English).
* @param {boolean} [props.supportsUrlParameters] - Set to true if you want to support URL Parameters to configure the Map Template.
* @param {boolean} [props.useKeyboard] - If running the Map Template as a kiosk, set this prop to true and it will prompt a keyboard.
* @param {number} [props.timeout] - If you want the Map Template to reset map position and UI elements to the initial state after some time of inactivity, use this to specify the number of seconds of inactivity before resetting.
* @param {number} [props.miTransitionLevel] - The zoom level on which to transition from Mapbox to MapsIndoors data. Default value is 17. This feature is only available for Mapbox.
* @param {boolean} [props.searchAllVenues] - If you want to perform search across all venues in the solution.
* @param {boolean} [props.hideNonMatches] - Determine whether the locations on the map should be filtered (only show the matched locations and hide the rest) or highlighted (show all locations and highlight the matched ones with a red dot by default). If set to true, the locations will be filtered.
* @param {boolean} [props.showRoadNames] - A boolean parameter that dictates whether Mapbox road names should be shown. By default, Mapbox road names are hidden when MapsIndoors data is shown. It is dictated by `mi-transition-level` which default value is 17.
* @param {boolean} [props.showExternalIDs] - Determine whether the location details on the map should have an external ID visible. The default value is set to false.
* @param {boolean} [props.searchExternalLocations] - If you want to perform search for external locations in the Wayfinding mode. If set to true, Mapbox/Google places will be displayed depending on the Map Provider you are using. If set to false, the results returned will only be MapsIndoors results. The default is true.
* @param {string} [props.center] - Specifies the coordinates where the map should load, represented as longitude and latitude values separated by a comma. If the specified coordinates intersect with a Venue, that Venue will be set as the current Venue.
* @param {boolean} [props.useAppTitle] - Specifies if the Map Template should set the document title as defined in the App Config. The default value is set to false.
* @param {boolean} [props.showMapMarkers] - Specifies if the Map Template should show the base map providers Map Markers. The default value is set to true.
* @param {string} [props.mapboxMapStyle] - Specifies the Mapbox Map Style to use. The default value is set to "mapbox://styles/mapbox/standard".
*/
function MapTemplate({ apiKey, gmApiKey, mapboxAccessToken, venue, locationId, primaryColor, logo, appUserRoles, directionsFrom, directionsTo, externalIDs, tileStyle, startZoomLevel, bearing, pitch, gmMapId, useMapProviderModule, kioskOriginLocationId, language, supportsUrlParameters, useKeyboard, timeout, miTransitionLevel, category, searchAllVenues, hideNonMatches, showRoadNames, showExternalIDs, searchExternalLocations, center, useAppTitle, showMapMarkers, mapboxMapStyle, devicePosition }) {
const [userSelectedLanguage, setUserSelectedLanguage] = useState(false);
const [mapOptions, setMapOptions] = useState({ brandingColor: primaryColor });
const setApiKey = useSetRecoilState(apiKeyState);
const setGmApiKey = useSetRecoilState(gmApiKeyState);
const setMapboxAccessToken = useSetRecoilState(mapboxAccessTokenState);
const [isMapReady, setMapReady] = useRecoilState(isMapReadyState);
const [venuesInSolution, setVenuesInSolution] = useRecoilState(venuesInSolutionState);
const [currentLocation, setCurrentLocation] = useRecoilState(currentLocationState);
const categories = useRecoilValue(categoriesState);
const setLocationId = useSetRecoilState(locationIdState);
const [color, setPrimaryColor] = useRecoilState(primaryColorState);
const setLogo = useSetRecoilState(logoState);
const setGmMapId = useSetRecoilState(gmMapIdState);
const mapsIndoorsInstance = useRecoilValue(mapsIndoorsInstanceState);
const [currentLanguage, setCurrentLanguage] = useRecoilState(languageState);
const setKioskLocation = useSetRecoilState(kioskLocationState);
const setKioskOriginLocationId = useSetRecoilState(kioskOriginLocationIdState);
const setTimeoutValue = useSetRecoilState(timeoutState);
const isInactive = useInactive(); // Hook to detect if user is inactive. Used in combination with timeout prop to reset the Map Template to initial values after a specified time.
const setSupportsUrlParameters = useSetRecoilState(supportsUrlParametersState);
const setUseKeyboard = useSetRecoilState(useKeyboardState);
const setMiTransitionLevel = useSetRecoilState(miTransitionLevelState);
const setSelectedCategory = useSetRecoilState(selectedCategoryState);
const setSearchAllVenues = useSetRecoilState(searchAllVenuesState);
const setCategory = useSetRecoilState(categoryState);
const setHideNonMatches = useSetRecoilState(hideNonMatchesState);
const setshowExternalIDs = useSetRecoilState(showExternalIDsState);
const setShowRoadNames = useSetRecoilState(showRoadNamesState);
const setSearchExternalLocations = useSetRecoilState(searchExternalLocationsState);
const setCenter = useSetRecoilState(centerState);
const [viewModeSwitchVisible, setViewModeSwitchVisible] = useState();
const mapClickActionRef = useRef();
const setWayfindingLocation = useSetRecoilState(wayfindingLocationState);
const qrCodeLink = useRecoilValue(qrCodeLinkState)
const [showVenueSelector, setShowVenueSelector] = useState(true);
const [showPositionControl, setShowPositionControl] = useState(true);
const directionsFromLocation = useLocationForWayfinding(directionsFrom);
const directionsToLocation = useLocationForWayfinding(directionsTo);
const [isMapPositionInvestigating, setIsMapPositionInvestigating] = useState(false);
// The filtered locations by external id, if present.
const setFilteredLocationsByExternalID = useSetRecoilState(filteredLocationsByExternalIDState);
// The filtered locations that the user sets when selecting a category/location.
const [filteredLocations, setFilteredLocations] = useRecoilState(filteredLocationsState);
// Holds a copy of the initially filtered locations.
const [initialFilteredLocations, setInitialFilteredLocations] = useState();
const [appConfig, setAppConfig] = useRecoilState(appConfigState);
const setSolution = useSetRecoilState(solutionState);
const setTileStyle = useSetRecoilState(tileStyleState);
const setStartZoomLevel = useSetRecoilState(startZoomLevelState);
const setBearing = useSetRecoilState(bearingState);
const setPitch = useSetRecoilState(pitchState);
const isDesktop = useIsDesktop();
const resetState = useReset();
const [pushAppView, goBack, currentAppView, currentAppViewPayload, appStates, resetAppHistory] = useAppHistory();
// Indicate if the MapsIndoors JavaScript SDK is available.
const [mapsindoorsSDKAvailable, setMapsindoorsSDKAvailable] = useState(false);
const showLegendDialog = useRecoilValue(isLegendDialogVisibleState);
// The reset count is used to add a new key to the sidebar or bottomsheet, forcing it to re-render from scratch when resetting the Map Template.
const [resetCount, setResetCount] = useState(0);
const [setCurrentVenueName, updateCategories] = useCurrentVenue();
const finishRoute = useOnRouteFinished();
const setErrorMessage = useSetRecoilState(notificationMessageState);
const mapType = useRecoilValue(mapTypeState);
const isKiosk = useIsKioskContext();
/**
* Ensure that MapsIndoors Web SDK is available.
*
* @returns {Promise}
*/
function initializeMapsIndoorsSDK() {
return new Promise((resolve) => {
if (window.mapsindoors !== undefined) {
return resolve();
}
const miSdkApiTag = document.createElement('script');
miSdkApiTag.setAttribute('type', 'text/javascript');
// Remember to update the root index.html with the same version / integrity
miSdkApiTag.setAttribute('src', 'https://app.mapsindoors.com/mapsindoors/js/sdk/4.57.0/mapsindoors-4.57.0.js.gz');
miSdkApiTag.setAttribute('integrity', 'sha384-Hxm9bx6t+2luBNdH7oGaUAgcZH+FMgbKfltKDlJYJsGbFnXcWH0bm6ZigXLgFmQg');
miSdkApiTag.setAttribute('crossorigin', 'anonymous');
document.body.appendChild(miSdkApiTag);
miSdkApiTag.onload = () => {
resolve();
}
});
}
// On initial load, set currentLanguage from URL prop or appConfig if not already set by user.
// This allows user selection to always take precedence after first interaction.
// Note: On reload, language will revert to URL or appConfig unless user selects again.
useEffect(() => {
if (!currentLanguage) {
if (language) {
setCurrentLanguage(language);
} else if (appConfig?.appSettings?.language) {
setCurrentLanguage(appConfig.appSettings.language);
}
}
}, [language, appConfig, currentLanguage, setCurrentLanguage]);
/*
* If the app is inactive, run code to reset UI and state.
*/
useEffect(() => {
if (isInactive) {
resetStateAndUI();
}
}, [isInactive]);
/**
* Wait for the MapsIndoors JS SDK to be initialized, then set the mapsindoorsSDKAvailable state to true.
*/
useEffect(() => {
initializeMapsIndoorsSDK().then(() => {
setMapsindoorsSDKAvailable(true);
});
return () => {
setInitialFilteredLocations();
}
}, []);
/*
* React on changes in the currentLanguage (from Recoil).
* If it is undefined, try to use the browser language. It will fall back to English if the language is not supported.
*/
useEffect(() => {
if (mapsindoorsSDKAvailable) {
// Sets language to use. Priority: currentLanguage -> language prop -> App Config -> browser's default language.
const languageToUse = currentLanguage ?? language ?? appConfig?.appSettings?.language ?? navigator.language;
// Set the language on the MapsIndoors SDK in order to get eg. Mapbox and Google directions in that language.
// The MapsIndoors data only accepts the first part of the IETF language string, hence the split.
window.mapsindoors.MapsIndoors.setLanguage(languageToUse.split('-')[0]);
// If relevant, fetch venues, categories and the current location again to get them in the new language
window.mapsindoors.services.LocationsService.once('update_completed', () => {
if (categories.length > 0) {
updateCategories();
}
if (venuesInSolution.length > 0) {
window.mapsindoors.services.VenuesService.getVenues().then(venuesResult => {
venuesResult = venuesResult.map(venue => {
venue.image = appConfig.venueImages[venue.name.toLowerCase()];
return venue;
});
setVenuesInSolution(venuesResult);
});
}
if (currentLocation) {
window.mapsindoors.services.LocationsService.getLocation(currentLocation.id).then(location => setCurrentLocation(location));
}
});
// Ensure MapsIndoors uses the user's selected language if supported,
// so all map content and UI are localized accordingly.
if (!i18n.language || i18n.language !== languageToUse) {
if (!i18n.isInitialized) {
initI18n(languageToUse);
} else {
i18n.changeLanguage(languageToUse);
}
}
}
}, [currentLanguage, language, mapsindoorsSDKAvailable, appConfig]);
/**
* React on changes in the MapsIndoors API key by fetching the required data.
*/
useEffect(() => {
if (mapsindoorsSDKAvailable) {
setApiKey(apiKey);
setMapReady(false);
window.mapsindoors.MapsIndoors.setMapsIndoorsApiKey(apiKey);
Promise.all([
// Fetch all Venues in the Solution
window.mapsindoors.services.VenuesService.getVenues(),
// Fetch the App Config belonging to the given API key. This is needed for checking access tokens and Venue images.
window.mapsindoors.services.AppConfigService.getConfig().then(appConfigResult => {
setAppConfig(appConfigResult); // We need this as early as possible
return appConfigResult;
}),
// Fetch solution info in order to see what modules are enabled
window.mapsindoors.services.SolutionsService.getSolution().then(solutionResult => {
setSolution(solutionResult);
return solutionResult;
}),
// Ensure a minimum waiting time of 1 second
new Promise(resolve => setTimeout(resolve, 1000))
]).then(([venuesResult, appConfigResult]) => {
venuesResult = venuesResult.map(venue => {
venue.image = appConfigResult.venueImages[venue.name.toLowerCase()];
return venue;
});
setVenuesInSolution(venuesResult);
});
setMapReady(false);
}
}, [apiKey, mapsindoorsSDKAvailable]);
/*
* Set map provider access token / API key based on props and app config.
*/
useEffect(() => {
if (mapsindoorsSDKAvailable && appConfig) {
if (
isNullOrUndefined(mapboxAccessToken) &&
isNullOrUndefined(gmApiKey) &&
isNullOrUndefined(appConfig?.appSettings?.mapboxAccessToken) &&
isNullOrUndefined(appConfig?.appSettings?.gmKey)
) {
setErrorMessage({ text: 'Please provide a Mapbox Access Token or Google Maps API key to show a map.', type: 'error' });
} else {
setMapboxAccessToken(mapboxAccessToken || appConfig.appSettings?.mapboxAccessToken);
setGmApiKey(gmApiKey || appConfig.appSettings?.gmKey);
}
}
}, [gmApiKey, mapboxAccessToken, mapsindoorsSDKAvailable, appConfig]);
/*
* React on changes in the app user roles prop.
*/
useEffect(() => {
if (mapsindoorsSDKAvailable) {
window.mapsindoors.services.SolutionsService.getUserRoles().then(userRoles => {
const roles = userRoles.filter(role => appUserRoles?.includes(role.name));
window.mapsindoors.MapsIndoors.setUserRoles(roles);
});
}
}, [appUserRoles, mapsindoorsSDKAvailable]);
/*
* React on changes in the externalIDs prop.
* Get the locations by external IDs, if present.
*/
useEffect(() => {
if (mapsindoorsSDKAvailable) {
if (externalIDs) {
window.mapsindoors.services.LocationsService.getLocationsByExternalId(externalIDs).then(locations => {
setFilteredLocationsByExternalID(locations);
});
} else {
setFilteredLocationsByExternalID([]);
}
}
}, [externalIDs, mapsindoorsSDKAvailable]);
/*
* React on changes to the locationId prop.
* Set as current location and change the venue according to the venue that the location belongs to.
*/
useEffect(() => {
if (mapsindoorsSDKAvailable) {
setLocationId(locationId);
if (locationId) {
window.mapsindoors.services.LocationsService.getLocation(locationId).then(location => {
if (location) {
setCurrentVenueName(location.properties.venueId);
setCurrentLocation(location);
}
});
}
}
}, [locationId, mapsindoorsSDKAvailable, resetCount]);
/*
* React to changes in the gmMapId prop.
*/
useEffect(() => {
if (mapsindoorsSDKAvailable) {
setGmMapId(gmMapId);
}
}, [gmMapId, mapsindoorsSDKAvailable]);
/*
* React to changes in the currentAppView in order to set various global states.
*
* We need to use a ref for the map click action, as it is used in the locationClicked function,
* which is caused by a MapsIndoors JS SDK event, which comes with the risk of reading stale state.
*/
useEffect(() => {
switch (currentAppView) {
case appStates.SEARCH:
case appStates.EXTERNALIDS:
case appStates.VENUE_SELECTOR:
mapClickActionRef.current = mapClickActions.SetCurrentLocation;
break;
case appStates.LOCATION_DETAILS:
if (currentAppViewPayload && !currentLocation) {
// If there is a history payload and the current location is not set, set it
setCurrentLocation(currentAppViewPayload);
}
mapClickActionRef.current = mapClickActions.SetCurrentLocation;
break;
case appStates.WAYFINDING:
mapClickActionRef.current = mapClickActions.SetWayfindingLocation;
break;
case appStates.DIRECTIONS:
mapClickActionRef.current = mapClickActions.None;
break;
}
// Reset all the filters when in directions mode.
// Store the filtered locations in another state, to be able to access them again.
if (currentAppView === appStates.DIRECTIONS) {
setInitialFilteredLocations(filteredLocations)
setFilteredLocations([]);
} else {
// Apply the previously filtered locations to the map when navigating outside the directions.
setFilteredLocations(initialFilteredLocations);
}
}, [currentAppView]);
/*
* React on changes in the venue prop. If not defined, check if it is defined in app config.
*/
useEffect(() => {
setCurrentVenueName(venue ?? appConfig?.appSettings?.venue);
}, [venue, appConfig]);
/*
* React on changes in the tile style prop.
*/
useEffect(() => {
setTileStyle(tileStyle);
}, [tileStyle]);
/*
* React on changes in the primary color prop. If not defined, check if it is defined in app config. Otherwise set to default color.
*/
useEffect(() => {
const defaultPrimaryColor = '#003C3B'; // --brand-colors-dark-pine-100 from MIDT
setPrimaryColor(primaryColor ?? appConfig?.appSettings?.primaryColor ?? defaultPrimaryColor);
}, [primaryColor, appConfig]);
/*
* React on changes in the map options props (primary color, showRoadNames, miTransitionLevel).
* This effect updates the mapOptions state accordingly.
*/
useEffect(() => {
setMapOptions({
brandingColor: color,
// Ensure showRoadNames and showMapMarkers are booleans, even if appConfig.appSettings.showRoadNames/showMapMarkers is a string
showRoadNames:
showRoadNames !== undefined
? showRoadNames
: (typeof appConfig?.appSettings?.showRoadNames === 'string'
? appConfig.appSettings.showRoadNames.toLowerCase() === 'true'
: appConfig?.appSettings?.showRoadNames),
showMapMarkers:
showMapMarkers !== undefined
? showMapMarkers
: (typeof appConfig?.appSettings?.showMapMarkers === 'string'
? appConfig.appSettings.showMapMarkers.toLowerCase() === 'true'
: appConfig?.appSettings?.showMapMarkers),
miTransitionLevel: miTransitionLevel,
// If ignoreViewportBounds is true, we would like to see the map at the minimum zoom level (World Map).
minZoom: appConfig?.appSettings?.minZoom ?? ZoomLevelValues.minZoom,
mapboxMapStyle: appConfig?.appSettings?.mapboxMapStyle || mapboxMapStyle,
// Boolean from the App Config comes as a string. We need to return clean boolean value based on that.
enableFullScreenButton:
typeof appConfig?.appSettings?.enableFullScreenButton === 'string'
? appConfig.appSettings.enableFullScreenButton.trim().toLowerCase() === 'true'
: !!appConfig?.appSettings?.enableFullScreenButton
})
}, [primaryColor, showRoadNames, miTransitionLevel, color, showMapMarkers, appConfig]);
/*
* React on changes in the start zoom level prop. If not defined, check if it is defined in app config.
*/
useEffect(() => {
setStartZoomLevel(startZoomLevel ?? appConfig?.appSettings?.startZoomLevel);
}, [startZoomLevel, appConfig]);
/*
* React on changes in the pitch prop. If not defined, check if it is defined in app config.
* If the pitch is not set, set it to 45 degrees if the view mode switch is visible.
*/
useEffect(() => {
const desiredPitch = pitch ?? appConfig?.appSettings?.pitch ?? null;
if (!isNullOrUndefined(desiredPitch)) {
setPitch(desiredPitch);
} else if (viewModeSwitchVisible) {
setPitch(45);
}
}, [pitch, viewModeSwitchVisible, appConfig]);
/*
* React on changes in the bearing prop. If not defined, check if it is defined in app config.
*/
useEffect(() => {
setBearing(bearing ?? appConfig?.appSettings?.bearing ?? null);
}, [bearing, appConfig]);
/*
* React on changes in the logo prop. If not defined, check if it is defined in app config. Otherwise set to default logo.
*/
useEffect(() => {
const defaultLogo = 'https://app.mapsindoors.com/mapsindoors/gfx/mapspeople-logo/mapspeople-pin.svg';
if (appConfig) {
setLogo(logo ?? appConfig?.appSettings?.logo ?? defaultLogo);
}
}, [logo, appConfig]);
/*
* React on changes in the miTransitionLevel prop.
*/
useEffect(() => {
setMiTransitionLevel(miTransitionLevel);
}, [miTransitionLevel]);
/*
* React on changes in the current location prop.
* Apply location selection if the current location exists and is not the same as the kioskOriginLocationId.
* Gated behind isMapReady to ensure selectLocation() is called AFTER the initial viewState.update(),
* preventing the selection pin from being baked into the main source (where deselectLocation can't clear it).
*/
useEffect(() => {
if (!isMapReady) return;
if (currentLocation && currentLocation.id !== kioskOriginLocationId) {
if (mapsIndoorsInstance?.selectLocation) {
mapsIndoorsInstance.highlight?.([]);
const map = mapsIndoorsInstance.getMap();
if (mapType === mapTypes.Mapbox) {
map.once('idle', () => mapsIndoorsInstance.selectLocation(currentLocation));
} else {
mapsIndoorsInstance.selectLocation(currentLocation);
}
}
} else {
if (mapsIndoorsInstance?.deselectLocation) {
mapsIndoorsInstance.deselectLocation();
}
}
}, [currentLocation, mapsIndoorsInstance, isMapReady, mapType]);
/**
* React on changes to the app config.
* If the removeMapboxExtrudedBuildings is true, set the extruded buildings visibility to false.
*/
useEffect(() => {
if (mapsIndoorsInstance && appConfig?.appSettings?.removeMapboxExtrudedBuildings === 'true') {
mapsIndoorsInstance?.getMapView()?.setExtrudedBuildingsVisibility(false);
}
}, [mapsIndoorsInstance, appConfig]);
/*
* React on changes to the kioskOriginLocationId prop.
*/
useEffect(() => {
if (mapsindoorsSDKAvailable) {
setKioskOriginLocationId(kioskOriginLocationId);
if (kioskOriginLocationId) {
window.mapsindoors.services.LocationsService.getLocation(kioskOriginLocationId).then(kioskLocation => {
setCurrentVenueName(kioskLocation.properties.venueId);
setKioskLocation(kioskLocation);
mapsIndoorsInstance?.setNonCollidingLocation(kioskLocation)
})
} else {
setKioskLocation();
}
if (kioskOriginLocationId && isDesktop) {
setShowVenueSelector(false);
setShowPositionControl(false);
} else {
setShowVenueSelector(true);
setShowPositionControl(true);
}
}
}, [kioskOriginLocationId, mapsindoorsSDKAvailable, mapsIndoorsInstance]);
/*
* React on changes to the timeout prop
*/
useEffect(() => {
setTimeoutValue(timeout);
}, [timeout]);
/*
* React on changes in the supportsUrlParameters prop.
*/
useEffect(() => {
setSupportsUrlParameters(supportsUrlParameters);
}, [supportsUrlParameters]);
/*
* React on changes to the useKeyboard prop.
* Show keyboard only in a kiosk context.
*/
useEffect(() => {
if (useKeyboard && kioskOriginLocationId) {
setUseKeyboard(useKeyboard);
}
}, [useKeyboard, kioskOriginLocationId]);
/*
* React on changes in the category prop.
* Check if the category property matches with any of the existing categories.
*/
useEffect(() => {
if (mapsindoorsSDKAvailable && category && categories.find((matched) => matched[0] === category)) {
setSelectedCategory(category);
}
}, [category, categories, mapsindoorsSDKAvailable]);
/*
* React on changes to the searchAllVenues prop.
*/
useEffect(() => {
setSearchAllVenues(searchAllVenues);
}, [searchAllVenues]);
/*
* React on changes to the hideNonMatches prop.
*/
useEffect(() => {
setHideNonMatches(hideNonMatches);
}, [hideNonMatches]);
/*
* React on changes to the showExternalIDs prop.
*/
useEffect(() => {
setshowExternalIDs(showExternalIDs);
}, [showExternalIDs]);
/*
* React on changes to the showRoadNames prop.
*/
useEffect(() => {
setShowRoadNames(showRoadNames);
}, [showRoadNames])
/*
* React on changes to the searchExternalLocations prop.
*/
useEffect(() => {
const externalLocationsConfig = appConfig?.appSettings?.searchExternalLocations;
const showExternalLocations = externalLocationsConfig !== undefined ? externalLocationsConfig === 'true' : searchExternalLocations;
setSearchExternalLocations(showExternalLocations);
}, [searchExternalLocations, appConfig]);
/*
* React on changes to the center prop.
*/
useEffect(() => {
setCenter(center ?? appConfig?.appSettings?.center);
}, [center, appConfig]);
/*
* Sets document title based on useAppTitle and appConfig values.
*/
useEffect(() => {
if (useAppTitle === true && !isNullOrUndefined(appConfig?.appSettings?.title)) {
document.title = appConfig.appSettings.title;
}
}, [useAppTitle, appConfig])
/**
* When map position is known while initializing the data,
* set map to be ready.
*/
function mapPositionKnown() {
if (isMapReady === false) {
setMapReady(true);
}
}
/**
* Handle the clicked location on the map.
*
* @param {object} location
*/
function locationClicked(location) {
switch (mapClickActionRef.current) {
case mapClickActions.SetCurrentLocation:
// Do not set the current location if the clicked location is the same as the kioskOriginLocationId,
// due to the logic of displaying directions right away when selecting a location on the map, when in kiosk mode.
if (location.id !== kioskOriginLocationId) {
setCurrentLocation(location);
}
break;
case mapClickActions.SetWayfindingLocation:
setWayfindingLocation(location);
break;
case mapClickActions.None:
default:
// Intentionally left blank.
break;
}
}
/**
* Function that handles the reset of the state and UI.
*/
function resetStateAndUI() {
resetState();
resetAppHistory();
setResetCount(curr => curr + 1); // will force a re-render of bottom sheet and sidebar.
setSelectedCategory(null); // unselect category when route is finished
}
/**
* Function that handles the finishing of route.
*/
function onRouteFinish() {
finishRoute();
resetAppHistory();
setResetCount(curr => curr + 1); // will force a re-render of bottom sheet and sidebar.
setSelectedCategory(null); // unselect category when route is finished
}
/*
* React on changes in the category prop.
* Check if the category property matches with any of the existing categories.
* Indicate the existence of the category as a prop or query parameter by setting the "setCategory" to true.
*/
useEffect(() => {
if (mapsindoorsSDKAvailable && category && categories.find((matched) => matched[0] === category)) {
setSelectedCategory(category);
setCategory(category);
}
}, [category, categories, mapsindoorsSDKAvailable]);
// On initial load, if a language prop is provided and user hasn't explicitly selected a language,
// set the current language to the prop value. This allows the URL language to take effect
// until the user makes a selection. Note: If the page is reloaded, the language will
// revert to the URL-provided value unless the user selects a different language again.
useEffect(() => {
if (!userSelectedLanguage) {
if (language && currentLanguage !== language) {
setCurrentLanguage(language);
} else if (!language && appConfig?.appSettings?.language && currentLanguage !== appConfig.appSettings.language) {
setCurrentLanguage(appConfig.appSettings.language);
}
}
}, [language, appConfig, currentLanguage, setCurrentLanguage, userSelectedLanguage]);
return (
<GeminiProvider enabled={appConfig?.appSettings?.enableChat === 'true'}>
<div className={`mapsindoors-map
${currentAppView === appStates.DIRECTIONS ? 'mapsindoors-map--hide-elements' : 'mapsindoors-map--show-elements'}
${(venuesInSolution.length > 1 && showVenueSelector) ? '' : 'mapsindoors-map--hide-venue-selector'}
${showPositionControl ? 'mapsindoors-map--show-my-position' : 'mapsindoors-map--hide-my-position'}
${isKiosk ? 'mapsindoors-map--kiosk' : ''}
${(currentAppView === appStates.CHAT && !isDesktop) ? 'mapsindoors-map--hide-map-controls' : ''}`}>
<Notification />
{!isMapReady && <SplashScreen />}
{venuesInSolution.length > 1 && showVenueSelector && <VenueSelector
onOpen={() => pushAppView(appStates.VENUE_SELECTOR)}
onClose={() => goBack()}
active={currentAppView === appStates.VENUE_SELECTOR}
/>}
{qrCodeLink && <QRCodeDialog />}
{showLegendDialog && <LegendDialog />}
<ChatButton
pushAppView={pushAppView}
currentAppView={currentAppView}
appViews={appStates}
/>
{isMapPositionInvestigating &&
<Fragment key={resetCount}>
{isDesktop &&
<Sidebar
directionsFromLocation={directionsFromLocation}
directionsToLocation={directionsToLocation}
pushAppView={pushAppView}
currentAppView={currentAppView}
appViews={appStates}
onRouteFinished={() => onRouteFinish()}
/>
}
{!isDesktop &&
<BottomSheet
directionsFromLocation={directionsFromLocation}
directionsToLocation={directionsToLocation}
pushAppView={pushAppView}
currentAppView={currentAppView}
appViews={appStates}
onRouteFinished={() => onRouteFinish()}
/>
}
</Fragment>
}
<MapWrapper
useMapProviderModule={useMapProviderModule}
onMapPositionKnown={() => mapPositionKnown()}
onMapPositionInvestigating={() => setIsMapPositionInvestigating(true)}
onLocationClick={(location) => locationClicked(location)}
onViewModeSwitchKnown={visible => setViewModeSwitchVisible(visible)}
resetCount={resetCount}
mapOptions={mapOptions}
gmMapId={gmMapId}
isWayfindingOrDirections={currentAppView === appStates.WAYFINDING || currentAppView === appStates.DIRECTIONS}
currentLanguage={currentLanguage}
setLanguage={(languageToSet) => {
setCurrentLanguage(languageToSet);
setUserSelectedLanguage(true);
}}
devicePosition={devicePosition}
/>
</div>
</GeminiProvider>
);
}
export default MapTemplate;