What You’ll Build
By the end of this guide, you’ll have a map that:- Displays an interactive Google Map
- Shows multiple markers at different locations
- Opens info windows when markers are clicked
- Centers on a specific location
- Handles loading and error states
Prerequisites
Before starting, ensure you have:- Installed
@react-google-maps/api(see Installation) - A valid Google Maps API key
- React 16.8 or higher
Step-by-Step Guide
Create the map component
Create a new file for your map component. We’ll start with a basic map display.
components/Map.tsx
We use
useMemo for center and containerStyle to maintain stable references and prevent unnecessary re-renders.Add markers to the map
Import the
Marker component and add markers for multiple locations.components/Map.tsx
Add interactive info windows
Add
InfoWindow components that open when users click markers.components/Map.tsx
We use
useCallback for event handlers to maintain stable function references and prevent unnecessary re-renders.Add map instance tracking
Track the map instance to enable programmatic map control.
components/Map.tsx
Complete Example
Here’s the full working code for reference:Understanding the Code
API Loading
useJsApiLoader hook:
- Loads the Google Maps JavaScript API asynchronously
- Returns
isLoadedwhen ready - Returns
loadErrorif loading fails - Only loads the API once, even if the component re-renders
Map Configuration
mapContainerStyle: CSS styles for the map container (must include height)center: Initial center coordinates of the mapzoom: Initial zoom level (1-20, where 1 is world view)onLoad: Callback when map is readyonUnmount: Cleanup callback when map unmounts
Marker Rendering
GoogleMap. Each marker:
- Needs a unique
keyprop - Uses
positionto set its location - Can handle click events with
onClick
Info Windows
- Display custom React content
- Use conditional rendering to show/hide
- Can be anchored to markers or positions
- Call
onCloseClickwhen the user closes them
Best Practices
Memoization
Event Handlers
Loading Libraries
Common Customizations
Custom Map Styles
Apply custom styling to your map:Custom Marker Icons
Map Click Events
Next Steps
Now that you have a working map, explore more advanced features:Components
Explore all available components like Polyline, Polygon, Circle, and more
Hooks
Learn about useGoogleMap and other utility hooks
Directions
Add routing and directions to your map
Places
Integrate place search and autocomplete