0
# React Google Maps API
1
2
React Google Maps API is a comprehensive TypeScript library that provides React components and hooks for seamlessly integrating Google Maps functionality into React applications. The library offers a declarative approach to building interactive maps with full type safety and extensive event handling.
3
4
## Package Information
5
6
- **Package Name**: @react-google-maps/api
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install @react-google-maps/api`
10
11
## Core Imports
12
13
```typescript
14
import {
15
GoogleMap,
16
LoadScript,
17
Marker,
18
InfoWindow,
19
useLoadScript,
20
useGoogleMap
21
} from "@react-google-maps/api";
22
```
23
24
For CommonJS:
25
26
```javascript
27
const {
28
GoogleMap,
29
LoadScript,
30
Marker,
31
InfoWindow,
32
useLoadScript,
33
useGoogleMap
34
} = require("@react-google-maps/api");
35
```
36
37
## Basic Usage
38
39
```typescript
40
import React from 'react';
41
import { GoogleMap, LoadScript, Marker, InfoWindow } from '@react-google-maps/api';
42
43
const mapContainerStyle = {
44
width: '100%',
45
height: '400px'
46
};
47
48
const center = {
49
lat: 40.7128,
50
lng: -74.0060
51
};
52
53
function MyMapComponent() {
54
const [selectedMarker, setSelectedMarker] = React.useState(null);
55
56
return (
57
<LoadScript googleMapsApiKey="YOUR_API_KEY">
58
<GoogleMap
59
mapContainerStyle={mapContainerStyle}
60
center={center}
61
zoom={10}
62
>
63
<Marker
64
position={center}
65
onClick={() => setSelectedMarker(center)}
66
/>
67
68
{selectedMarker && (
69
<InfoWindow
70
position={selectedMarker}
71
onCloseClick={() => setSelectedMarker(null)}
72
>
73
<div>
74
<h2>New York City</h2>
75
<p>The Big Apple!</p>
76
</div>
77
</InfoWindow>
78
)}
79
</GoogleMap>
80
</LoadScript>
81
);
82
}
83
```
84
85
## Architecture
86
87
React Google Maps API is built around several key architectural components:
88
89
- **Script Loading System**: Multiple approaches for loading Google Maps JavaScript API (`LoadScript`, `LoadScriptNext`, `useLoadScript`, `useJsApiLoader`)
90
- **Component Hierarchy**: All map components must be rendered within a `GoogleMap` container component
91
- **Context System**: Map instance is provided through React Context, accessible via `useGoogleMap` hook
92
- **Event-Driven Design**: Extensive event handling system with lifecycle callbacks (`onLoad`, `onUnmount`)
93
- **Type Safety**: Full TypeScript support with detailed interfaces for all Google Maps API types
94
- **Functional Variants**: Many components offer both class-based and functional hook-based implementations (with 'F' suffix)
95
96
## Capabilities
97
98
### Script Loading & Initialization
99
100
Script loading utilities for initializing the Google Maps JavaScript API with various configuration options and loading strategies.
101
102
```typescript { .api }
103
interface LoadScriptProps {
104
googleMapsApiKey: string;
105
libraries?: Libraries;
106
language?: string;
107
region?: string;
108
version?: string;
109
children?: React.ReactNode;
110
onLoad?: () => void;
111
onError?: (error: Error) => void;
112
}
113
114
function useLoadScript(options: UseLoadScriptOptions): {
115
isLoaded: boolean;
116
loadError: Error | undefined;
117
url: string;
118
};
119
```
120
121
[Script Loading](./script-loading.md)
122
123
### Core Map Component
124
125
The main GoogleMap component that renders the interactive map container and manages the Google Maps instance.
126
127
```typescript { .api }
128
interface GoogleMapProps {
129
children?: React.ReactNode;
130
id?: string;
131
mapContainerStyle?: React.CSSProperties;
132
mapContainerClassName?: string;
133
options?: google.maps.MapOptions;
134
center?: google.maps.LatLng | google.maps.LatLngLiteral;
135
zoom?: number;
136
onClick?: (e: google.maps.MapMouseEvent) => void;
137
onLoad?: (map: google.maps.Map) => void | Promise<void>;
138
onUnmount?: (map: google.maps.Map) => void | Promise<void>;
139
}
140
141
function GoogleMap(props: GoogleMapProps): JSX.Element;
142
function useGoogleMap(): google.maps.Map | null;
143
```
144
145
[Core Map](./core-map.md)
146
147
### Markers & Overlays
148
149
Components for displaying markers, info windows, and custom overlay content positioned on the map.
150
151
```typescript { .api }
152
interface MarkerProps {
153
position: google.maps.LatLng | google.maps.LatLngLiteral;
154
animation?: google.maps.Animation;
155
clickable?: boolean;
156
draggable?: boolean;
157
icon?: string | google.maps.Icon | google.maps.Symbol;
158
label?: string | google.maps.MarkerLabel;
159
onClick?: (e: google.maps.MapMouseEvent) => void;
160
onLoad?: (marker: google.maps.Marker) => void;
161
}
162
163
interface InfoWindowProps {
164
children?: React.ReactNode;
165
position?: google.maps.LatLng | google.maps.LatLngLiteral;
166
anchor?: google.maps.MVCObject;
167
options?: google.maps.InfoWindowOptions;
168
onCloseClick?: () => void;
169
}
170
```
171
172
[Markers & Overlays](./markers-overlays.md)
173
174
### Drawing & Shapes
175
176
Components for creating and managing geometric shapes, drawing tools, and interactive drawing functionality on the map.
177
178
```typescript { .api }
179
interface PolygonProps {
180
options?: google.maps.PolygonOptions;
181
path?: google.maps.LatLng[] | google.maps.LatLngLiteral[];
182
paths?: google.maps.LatLng[][] | google.maps.LatLngLiteral[][];
183
draggable?: boolean;
184
editable?: boolean;
185
onClick?: (e: google.maps.MapMouseEvent) => void;
186
onLoad?: (polygon: google.maps.Polygon) => void;
187
}
188
189
interface DrawingManagerProps {
190
options?: google.maps.drawing.DrawingManagerOptions;
191
drawingMode?: google.maps.drawing.OverlayType;
192
onOverlayComplete?: (e: google.maps.drawing.OverlayCompleteEvent) => void;
193
}
194
```
195
196
[Drawing & Shapes](./drawing-shapes.md)
197
198
### Map Layers
199
200
Layer components for displaying additional information overlays like traffic, transit routes, and heatmaps.
201
202
```typescript { .api }
203
interface TrafficLayerProps {
204
options?: google.maps.TrafficLayerOptions;
205
onLoad?: (trafficLayer: google.maps.TrafficLayer) => void;
206
}
207
208
interface HeatmapLayerProps {
209
data: google.maps.LatLng[] | google.maps.visualization.WeightedLocation[];
210
options?: google.maps.visualization.HeatmapLayerOptions;
211
onLoad?: (heatmapLayer: google.maps.visualization.HeatmapLayer) => void;
212
}
213
```
214
215
[Layers](./layers.md)
216
217
### Marker Clustering
218
219
Components for grouping nearby markers into clusters to improve performance and user experience with large marker datasets.
220
221
```typescript { .api }
222
interface MarkerClustererProps {
223
children: React.ReactNode;
224
options?: ClustererOptions;
225
onLoad?: (clusterer: Clusterer) => void;
226
}
227
228
interface GoogleMarkerClustererProps {
229
children: React.ReactNode;
230
options?: google.maps.MarkerClustererOptions;
231
onLoad?: (clusterer: google.maps.MarkerClusterer) => void;
232
}
233
```
234
235
[Clustering](./clustering.md)
236
237
### Google Maps Services
238
239
Service components for accessing Google Maps platform services like directions, distance matrix, and Street View.
240
241
```typescript { .api }
242
interface DirectionsServiceProps {
243
options: google.maps.DirectionsRequest;
244
callback: (
245
result: google.maps.DirectionsResult | null,
246
status: google.maps.DirectionsStatus
247
) => void;
248
onLoad?: (directionsService: google.maps.DirectionsService) => void;
249
}
250
251
interface DirectionsRendererProps {
252
directions?: google.maps.DirectionsResult;
253
options?: google.maps.DirectionsRendererOptions;
254
onLoad?: (directionsRenderer: google.maps.DirectionsRenderer) => void;
255
}
256
```
257
258
[Services](./services.md)
259
260
### Places Integration
261
262
Components for integrating Google Places API functionality, including autocomplete and place search capabilities.
263
264
```typescript { .api }
265
interface AutocompleteProps {
266
children: React.ReactNode;
267
bounds?: google.maps.LatLngBounds | google.maps.LatLngBoundsLiteral;
268
restrictions?: google.maps.places.ComponentRestrictions;
269
fields?: string[];
270
options?: google.maps.places.AutocompleteOptions;
271
onPlaceChanged?: () => void;
272
onLoad?: (autocomplete: google.maps.places.Autocomplete) => void;
273
}
274
275
interface StandaloneSearchBoxProps {
276
children: React.ReactNode;
277
bounds?: google.maps.LatLngBounds | google.maps.LatLngBoundsLiteral;
278
options?: google.maps.places.SearchBoxOptions;
279
onPlacesChanged?: () => void;
280
}
281
```
282
283
[Places](./places.md)
284
285
## Prerequisites
286
287
Before using React Google Maps API, ensure you have:
288
289
- **Google Maps JavaScript API Key**: Required for loading the Google Maps API
290
- Create an API key in [Google Cloud Console](https://console.cloud.google.com/)
291
- Enable Google Maps JavaScript API
292
- (Optional) Enable additional APIs: Places API, Directions API, Distance Matrix API
293
- **React Application**: Compatible with React 16.8+ (hooks support required)
294
- **TypeScript Support**: Package includes full TypeScript definitions
295
- **Internet Connection**: Required for loading Google Maps API scripts
296
297
## Common Patterns
298
299
### API Key Management
300
301
```typescript
302
// Environment variables (recommended)
303
const API_KEY = process.env.REACT_APP_GOOGLE_MAPS_API_KEY;
304
305
// Conditional loading based on environment
306
function App() {
307
if (!API_KEY) {
308
return <div>Please configure Google Maps API key</div>;
309
}
310
311
return (
312
<LoadScript googleMapsApiKey={API_KEY}>
313
<GoogleMap /* ... */ />
314
</LoadScript>
315
);
316
}
317
```
318
319
### Performance Optimization
320
321
```typescript
322
// Use LoadScript for entire app (recommended)
323
function App() {
324
return (
325
<LoadScript
326
googleMapsApiKey={API_KEY}
327
libraries={['places']} // Only load needed libraries
328
>
329
<Router>
330
<Routes>
331
<Route path="/map" element={<MapPage />} />
332
</Routes>
333
</Router>
334
</LoadScript>
335
);
336
}
337
338
// Alternative: useLoadScript for conditional loading
339
function MapComponent() {
340
const { isLoaded, loadError } = useLoadScript({
341
googleMapsApiKey: API_KEY,
342
libraries: ['places']
343
});
344
345
if (loadError) return <div>Error loading maps</div>;
346
if (!isLoaded) return <div>Loading maps...</div>;
347
348
return <GoogleMap /* ... */ />;
349
}
350
```
351
352
### Error Handling
353
354
```typescript
355
function MapWithErrorHandling() {
356
const [mapError, setMapError] = useState<string | null>(null);
357
358
return (
359
<LoadScript
360
googleMapsApiKey={API_KEY}
361
onError={() => setMapError('Failed to load Google Maps API')}
362
>
363
{mapError ? (
364
<div>Error: {mapError}</div>
365
) : (
366
<GoogleMap
367
onLoad={(map) => console.log('Map loaded successfully')}
368
onUnmount={(map) => console.log('Map unmounted')}
369
/>
370
)}
371
</LoadScript>
372
);
373
}
374
```
375
376
## Troubleshooting
377
378
### Common Issues
379
380
**API Key Errors**
381
- Ensure API key is valid and has proper permissions
382
- Check that Google Maps JavaScript API is enabled
383
- Verify billing is enabled for your Google Cloud project
384
- Add your domain to API key restrictions if using referrer restrictions
385
386
**Script Loading Issues**
387
- Use only one script loading method (`LoadScript`, `LoadScriptNext`, or `useLoadScript`)
388
- Avoid multiple LoadScript instances in the same application
389
- Check browser console for network errors or CSP violations
390
391
**Map Not Displaying**
392
- Ensure map container has explicit dimensions (width/height)
393
- Verify the map center coordinates are valid
394
- Check that the Google Maps API has finished loading before rendering
395
396
**TypeScript Errors**
397
- Install `@types/google.maps` if not already present
398
- Ensure you're importing types correctly: `google.maps.LatLng`
399
- Use the provided interfaces from this package for component props
400
401
**Performance Issues**
402
- Limit the number of markers rendered simultaneously (use clustering)
403
- Load only necessary libraries in the `libraries` array
404
- Use `React.memo()` for components that render many map elements
405
- Implement virtual scrolling for large datasets
406
407
### Migration from react-google-maps
408
409
```typescript
410
// Old (react-google-maps)
411
import { GoogleMap, withGoogleMap, withScriptjs } from "react-google-maps";
412
413
// New (@react-google-maps/api)
414
import { GoogleMap, LoadScript } from "@react-google-maps/api";
415
```
416
417
Key differences:
418
- No HOCs required (`withGoogleMap`, `withScriptjs`)
419
- Direct component usage with `LoadScript` wrapper
420
- Improved TypeScript support
421
- Better tree-shaking and smaller bundle size
422
- Hook-based API with `useLoadScript` and `useGoogleMap`
423
424
## Version Compatibility
425
426
- **React**: 16.8+ (hooks required), 17.x, 18.x, 19.x supported
427
- **Google Maps API**: Weekly, quarterly, and versioned releases supported
428
- **TypeScript**: 4.0+ recommended for full type support
429
- **Node.js**: 14+ for development builds
430
431
The package follows semantic versioning and maintains backward compatibility within major versions.