googlemaps / googlemaps/js-samples

Google Maps JavaScript API Bootstrap Loader Pattern for React/TypeScript Integration

Open
#1,914 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
TypeScript
Stars
805
Forks
836
PR merge metrics
No merged PRs in 30d

Description

I'm looking for the best practices for integrating Google Maps JavaScript API with React and TypeScript using the new bootstrap loader pattern.

Based on the official documentation, I see the bootstrap loader should be used:

```javascript

(g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})({
key: "YOUR_API_KEY",
v: "weekly",
});

```

And then use dynamic imports:
```typescript
const { Map } = await google.maps.importLibrary("maps") as google.maps.MapsLibrary;
const { AdvancedMarkerElement } = await google.maps.importLibrary("marker") as google.maps.MarkerLibrary;
```

However, I'm working on a project where I need to:
1. Load Google Maps script dynamically in a React component
2. Use TypeScript with proper type safety
3. Handle loading states and errors gracefully
4. Support features like Traffic Layer, Places Autocomplete, etc.

Could you provide or point to examples that show:
1. How to properly load the bootstrap script in a React app
2. TypeScript type definitions for the new `importLibrary` pattern
3. Error handling and loading states
4. Best practices for component lifecycle management

This would be very helpful for developers trying to migrate from the legacy loading patterns to the new bootstrap approach.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.