-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathMapWrapper.jsx
More file actions
361 lines (322 loc) · 17.3 KB
/
MapWrapper.jsx
File metadata and controls
361 lines (322 loc) · 17.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
import { useEffect, useState } from 'react';
import { useRecoilState, useRecoilValue, useSetRecoilState } from 'recoil';
import MIMap from '../MIMap/MIMap';
import { mapTypes } from '../../constants/mapTypes';
import useLiveData from '../../hooks/useLivedata';
import mapsIndoorsInstanceState from '../../atoms/mapsIndoorsInstanceState';
import userPositionState from '../../atoms/userPositionState';
import directionsServiceState from '../../atoms/directionsServiceState';
import mapTypeState from '../../atoms/mapTypeState';
import apiKeyState from '../../atoms/apiKeyState';
import gmApiKeyState from '../../atoms/gmApiKeyState';
import mapboxAccessTokenState from '../../atoms/mapboxAccessTokenState';
import filteredLocationsState from '../../atoms/filteredLocationsState';
import filteredLocationsByExternalIDState from '../../atoms/filteredLocationsByExternalIDState';
import currentLocationState from '../../atoms/currentLocationState';
import tileStyleState from '../../atoms/tileStyleState';
import positionControlState from '../../atoms/positionControlState';
import bearingState from '../../atoms/bearingState';
import pitchState from '../../atoms/pitchState';
import solutionState from '../../atoms/solutionState';
import notificationMessageState from '../../atoms/notificationMessageState';
import useMapBoundsDeterminer from '../../hooks/useMapBoundsDeterminer';
import hideNonMatchesState from '../../atoms/hideNonMatchesState';
import PropTypes from 'prop-types';
import ViewSelector from '../ViewSelector/ViewSelector';
import LanguageSelector from '../LanguageSelector/LanguageSelector.jsx';
import appConfigState from '../../atoms/appConfigState';
import isNullOrUndefined from '../../helpers/isNullOrUndefined';
import ResetKioskViewButton from '../ResetKioskViewButton/ResetKioskViewButton.jsx';
import { useIsKioskContext } from '../../hooks/useIsKioskContext';
MapWrapper.propTypes = {
onLocationClick: PropTypes.func,
onMapPositionKnown: PropTypes.func.isRequired,
useMapProviderModule: PropTypes.bool.isRequired,
onMapPositionInvestigating: PropTypes.func.isRequired,
onViewModeSwitchKnown: PropTypes.func.isRequired,
resetCount: PropTypes.number.isRequired,
mapOptions: PropTypes.object,
gmMapId: PropTypes.string,
isWayfindingOrDirections: PropTypes.bool,
currentLanguage: PropTypes.string,
setLanguage: PropTypes.func,
devicePosition: PropTypes.object
};
/**
* Private variable used for storing the tile style.
* Implemented due to the impossibility to use the React useState hook.
*/
let _tileStyle;
/**
* A wrapper component around the MIMap component.
* Contains logic for determining map provider (Google, Mapbox), map options, device position handling and setting up a directions service to use for showing directions.
*
* @param {Object} props
* @param {function} [props.onLocationClick] - Function that is run when a MapsIndoors Location is clicked. the Location will be sent along as first argument.
* @param {function} props.onMapPositionKnown - Function that is run when the map bounds was changed due to fitting to a Venue or Location.
* @param {boolean} props.useMapProviderModule - If you want to use the Map Provider set on your solution in the MapsIndoors CMS, set this to true.
* @param {function} onMapPositionInvestigating - Function that is run when the map position is being determined.
* @param {function} onViewModeSwitchKnown - Function that is run when the view mode switch is known (if it is to be shown of not).
* @param {number} resetCount - A counter that is incremented when the map should be reset.
* @param {object} props.mapOptions - Options for instantiating and styling the map as well as UI elements.
* @param {string} props.gmMapId - Google Maps Map ID for custom styling.
* @param {boolean} props.isWayfindingOrDirections - Whether wayfinding or directions is active or not.
* @param {string} props.currentLanguage - The currently selected language code.
* @param {function} props.setLanguage - Function to set the selected language.
* @param {object} [props.devicePosition] - Device position object with coords and timestamp for custom positioning.
* @returns
*/
function MapWrapper({ onLocationClick, onMapPositionKnown, useMapProviderModule, onMapPositionInvestigating, onViewModeSwitchKnown, resetCount, mapOptions, gmMapId, isWayfindingOrDirections, currentLanguage, setLanguage, devicePosition }) {
const apiKey = useRecoilValue(apiKeyState);
const gmApiKey = useRecoilValue(gmApiKeyState);
const mapboxAccessToken = useRecoilValue(mapboxAccessTokenState);
const [mapType, setMapType] = useRecoilState(mapTypeState);
const [mapsIndoorsInstance, setMapsIndoorsInstance] = useRecoilState(mapsIndoorsInstanceState);
const setUserPosition = useSetRecoilState(userPositionState);
const setDirectionsService = useSetRecoilState(directionsServiceState);
const filteredLocations = useRecoilValue(filteredLocationsState);
const filteredLocationsByExternalIDs = useRecoilValue(filteredLocationsByExternalIDState);
const currentLocation = useRecoilValue(currentLocationState);
const tileStyle = useRecoilValue(tileStyleState);
const bearing = useRecoilValue(bearingState);
const pitch = useRecoilValue(pitchState);
const setPositionControl = useSetRecoilState(positionControlState);
const solution = useRecoilValue(solutionState);
const setErrorMessage = useSetRecoilState(notificationMessageState);
const hideNonMatches = useRecoilValue(hideNonMatchesState);
const appConfig = useRecoilValue(appConfigState);
const [isViewSelectorVisible, setIsViewSelectorVisible] = useState(false);
const [isLanguageSelectorVisible, setIsLanguageSelectorVisible] = useState(false);
const isKiosk = useIsKioskContext();
useLiveData(apiKey);
const [mapPositionInvestigating, mapPositionKnown] = useMapBoundsDeterminer();
useEffect(() => {
if (!solution || (gmApiKey === null && mapboxAccessToken === null)) return;
/*
Which map type to load (Mapbox or Google Maps) is determined here, based on following decision table:
(note that some combinations can result in no map being loaded at all)
-----------------------------------------------------------------------------------------------------------------
useMapProviderModule Mapbox module enabled Mapbox Access Token Google Maps API key Map to load
prop value on solution is available is available
-----------------------------------------------------------------------------------------------------------------
true ✅ ✅ ✅ Mapbox
true ✅ ✅ ❌ Mapbox
true ✅ ❌ ✅ None
true ✅ ❌ ❌ None
true ❌ ✅ ✅ Google Maps
true ❌ ✅ ❌ None
true ❌ ❌ ✅ Google Maps
true ❌ ❌ ❌ None
false ✅ ✅ ✅ Mapbox
false ✅ ✅ ❌ Mapbox
false ✅ ❌ ✅ Google Maps
false ✅ ❌ ❌ Google Maps
false ❌ ✅ ✅ Mapbox
false ❌ ✅ ❌ Mapbox
false ❌ ❌ ✅ Google Maps
false ❌ ❌ ❌ Google Maps
*/
let mapTypeToUse;
const isMapboxModuleEnabled = solution.modules.map(module => module.toLowerCase()).includes('mapbox');
if (useMapProviderModule) {
if (isMapboxModuleEnabled) {
if (mapboxAccessToken) {
mapTypeToUse = mapTypes.Mapbox;
}
} else {
if (gmApiKey) {
mapTypeToUse = mapTypes.Google;
}
}
} else {
if (mapboxAccessToken) {
mapTypeToUse = mapTypes.Mapbox;
} else {
mapTypeToUse = mapTypes.Google;
}
}
if (mapTypeToUse) {
setMapType(mapTypeToUse);
} else {
// A good candidate for map type could not be determined.
setErrorMessage({ text: 'Please provide a Mapbox Access Token or Google Maps API key to show a map.', type: 'error' });
setMapType(undefined);
}
}, [gmApiKey, mapboxAccessToken, solution]);
/*
* When map position is investigating, run callback.
*/
useEffect(() => {
if (mapPositionInvestigating) {
onMapPositionInvestigating();
}
}, [mapPositionInvestigating]);
/*
* When map position is known, run callback.
*/
useEffect(() => {
if (mapPositionKnown) {
onMapPositionKnown();
}
}, [mapPositionKnown]);
/*
* Dynamically filter or highlight location based on the "filteredLocations", "filteredLocationsByExternalIDs" and "hideNonMatches" property.
*/
useEffect(() => {
if (!mapsIndoorsInstance) return;
const locations = filteredLocations || filteredLocationsByExternalIDs;
if (currentLocation || !locations || locations.length === 0) {
mapsIndoorsInstance.highlight?.([]);
return;
}
const locationIds = locations.map(location => location.id);
if (hideNonMatches || !mapsIndoorsInstance.highlight) {
mapsIndoorsInstance.filter(locationIds);
} else {
mapsIndoorsInstance.highlight(locationIds);
}
}, [filteredLocations, filteredLocationsByExternalIDs, mapsIndoorsInstance, hideNonMatches, currentLocation]);
/*
* React to changes in bearing and pitch props and set them on the map if mapsIndoorsInstance exists.
*/
useEffect(() => {
if (mapsIndoorsInstance) {
if (!isNaN(parseInt(pitch))) {
mapsIndoorsInstance.getMapView().tilt(parseInt(pitch));
}
if (!isNaN(parseInt(bearing))) {
mapsIndoorsInstance.getMapView().rotate(parseInt(bearing));
}
}
}, [bearing, pitch, mapsIndoorsInstance]);
/**
* Handle the tile style changes and the locationId property.
*
* @param {object} miInstance
*/
const onBuildingChanged = (miInstance) => {
onTileStyleChanged(miInstance);
}
/**
* Replace the default tile URL style to the incoming tile style.
*
* @param {object} miInstance
*/
const onTileStyleChanged = (miInstance) => {
if (miInstance && _tileStyle) {
let tileURL = miInstance.getTileURL();
if (tileURL) {
tileURL = miInstance.getTileURL().replace('default', _tileStyle);
// Replace the floor placeholder with the actual floor and set the tile URL on the MapView.
const tileStyleWithFloor = tileURL?.replace('{floor}', miInstance.getFloor());
miInstance.getMapView().setMapsIndoorsTileURL(tileStyleWithFloor);
}
}
}
/**
* React when MapsIndoors instance and position control is ready, and setup necessary objects.
*
* @param {object} miInstance
* @param {object} positionControl
*/
const onInitialized = (miInstance, positionControl, viewModeSwitchVisible) => {
// Detect when the mouse hovers over a location and store the hovered location
// If the location is non-selectable, remove the hovering by calling the unhoverLocation() method.
miInstance.on('mouseenter', () => {
const hoveredLocation = miInstance.getHoveredLocation()
if (hoveredLocation?.properties.locationSettings?.selectable === false) {
miInstance.unhoverLocation();
}
});
// TODO: Turn off visibility for building outline for demo purposes until the SDK supports Display Rules for Buildings too.
miInstance.setDisplayRule(['MI_BUILDING_OUTLINE'], { visible: false });
miInstance.on('click', location => onLocationClick(location));
miInstance.once('building_changed', () => onBuildingChanged(miInstance))
miInstance.on('floor_changed', () => onTileStyleChanged(miInstance));
setMapsIndoorsInstance(miInstance);
// Assign the miInstance to the mapsIndoorsInstance on the window interface.
window.mapsIndoorsInstance = miInstance;
// Create a custom event that is dispatched from the window interface.
const event = new CustomEvent('mapsIndoorsInstanceAvailable');
window.dispatchEvent(event);
// Initialize a Directions Service
let externalDirectionsProvider;
if (mapType === mapTypes.Google) {
externalDirectionsProvider = new window.mapsindoors.directions.GoogleMapsProvider();
} else if (mapType === mapTypes.Mapbox) {
externalDirectionsProvider = new window.mapsindoors.directions.MapboxProvider(mapboxAccessToken);
}
const directionsService = new window.mapsindoors.services.DirectionsService(externalDirectionsProvider);
setDirectionsService(directionsService);
setMapsIndoorsInstance(miInstance);
if (positionControl.nodeName === 'MI-MY-POSITION') {
// The Web Component needs to set up the listener with addEventListener
positionControl.addEventListener('position_received', positionInfo => {
if (positionInfo.detail.accurate === true) {
setUserPosition(positionInfo.detail.position);
}
});
positionControl.addEventListener('position_error', () => {
setUserPosition(null);
});
} else {
positionControl.on('position_received', positionInfo => {
if (positionInfo.accurate === true) {
setUserPosition(positionInfo.position);
}
});
positionControl.on('position_error', () => {
setUserPosition(null);
});
}
setPositionControl(positionControl);
onViewModeSwitchKnown(viewModeSwitchVisible);
}
/*
* React on changes in the tile style prop.
*/
useEffect(() => {
_tileStyle = tileStyle || 'default';
onTileStyleChanged(mapsIndoorsInstance);
}, [tileStyle]);
/**
* React on changes in appConfig and sets visibility of View Selector and visibility of Language Selector.
*/
useEffect(() => {
if (appConfig) {
if (isNullOrUndefined(appConfig?.appSettings?.viewSelector)) {
setIsViewSelectorVisible(false);
} else {
// Boolean from the App Config comes as a string. We need to return clean boolean value based on that.
setIsViewSelectorVisible(appConfig?.appSettings?.viewSelector.trim().toLowerCase() === 'true');
}
if (isNullOrUndefined(appConfig?.appSettings?.languageSelector)) {
setIsLanguageSelectorVisible(false);
} else {
// Boolean from the App Config comes as a string. We need to return clean boolean value based on that.
setIsLanguageSelectorVisible(appConfig?.appSettings?.languageSelector.trim().toLowerCase() === 'true');
}
}
}, [appConfig])
return (<>
{apiKey && mapType && <MIMap
apiKey={apiKey}
mapType={mapType}
mapboxAccessToken={mapType === mapTypes.Mapbox ? mapboxAccessToken : undefined}
gmApiKey={mapType === mapTypes.Google ? gmApiKey : undefined}
onInitialized={onInitialized}
resetUICounter={resetCount}
mapOptions={mapOptions}
gmMapId={gmMapId}
devicePosition={devicePosition}
isKiosk={isKiosk}
/>}
{/* Pass isWayfindingOrDirections prop to ViewSelector to disable interactions while wayfinding or directions is active*/}
{apiKey && mapType && <>
<ViewSelector isViewSelectorVisible={isViewSelectorVisible} isViewSelectorDisabled={isWayfindingOrDirections} />
<LanguageSelector currentLanguage={currentLanguage} setLanguage={setLanguage} isVisible={isLanguageSelectorVisible} />
<ResetKioskViewButton />
</>}
</>)
}
export default MapWrapper;