-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmapboxLoader.ts
More file actions
76 lines (64 loc) · 1.98 KB
/
mapboxLoader.ts
File metadata and controls
76 lines (64 loc) · 1.98 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
/**
* Mapbox GL JS loader utility
*
* Safely waits for window.mapboxgl to be available after the deferred
* script loads. Provides a consistent way for map components to initialize
* without race conditions.
*/
declare global {
interface Window {
mapboxgl?: any;
}
}
const MAPBOX_LOAD_TIMEOUT_MS = 5000;
export type MapboxLoadResult =
| { ready: true; mapboxgl: typeof import('mapbox-gl') }
| { ready: false; error: string };
/**
* Wait for Mapbox GL JS to be loaded and available on window.mapboxgl.
* Returns a promise that resolves with the mapboxgl object or rejects with an error.
*
* @param timeoutMs - Maximum time to wait (default: 5000ms)
* @returns Promise resolving to MapboxLoadResult
*/
export function waitForMapbox(timeoutMs = MAPBOX_LOAD_TIMEOUT_MS): Promise<MapboxLoadResult> {
return new Promise((resolve) => {
// Already loaded
if (window.mapboxgl) {
resolve({ ready: true, mapboxgl: window.mapboxgl });
return;
}
const startTime = Date.now();
function poll() {
if (window.mapboxgl) {
resolve({ ready: true, mapboxgl: window.mapboxgl });
return;
}
if (Date.now() - startTime >= timeoutMs) {
resolve({
ready: false,
error: `Mapbox GL JS failed to load within ${timeoutMs}ms. Check network connection.`,
});
return;
}
// Use requestAnimationFrame for smoother polling
requestAnimationFrame(poll);
}
// Start polling on next frame
requestAnimationFrame(poll);
});
}
/**
* React hook-friendly version that returns status for UI rendering.
* Components should call this once on mount and handle the result.
*/
export async function loadMapbox(): Promise<MapboxLoadResult> {
return waitForMapbox();
}
/**
* Synchronous check if Mapbox is currently available.
*/
export function isMapboxReady(): boolean {
return typeof window !== 'undefined' && !!window.mapboxgl;
}
export default { waitForMapbox, loadMapbox, isMapboxReady };