React.js Google Maps API integration with components and hooks for seamless Google Maps functionality
npx @tessl/cli install tessl/npm-react-google-maps--api@2.20.0React 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.
npm install @react-google-maps/apiimport {
GoogleMap,
LoadScript,
Marker,
InfoWindow,
useLoadScript,
useGoogleMap
} from "@react-google-maps/api";For CommonJS:
const {
GoogleMap,
LoadScript,
Marker,
InfoWindow,
useLoadScript,
useGoogleMap
} = require("@react-google-maps/api");import React from 'react';
import { GoogleMap, LoadScript, Marker, InfoWindow } from '@react-google-maps/api';
const mapContainerStyle = {
width: '100%',
height: '400px'
};
const center = {
lat: 40.7128,
lng: -74.0060
};
function MyMapComponent() {
const [selectedMarker, setSelectedMarker] = React.useState(null);
return (
<LoadScript googleMapsApiKey="YOUR_API_KEY">
<GoogleMap
mapContainerStyle={mapContainerStyle}
center={center}
zoom={10}
>
<Marker
position={center}
onClick={() => setSelectedMarker(center)}
/>
{selectedMarker && (
<InfoWindow
position={selectedMarker}
onCloseClick={() => setSelectedMarker(null)}
>
<div>
<h2>New York City</h2>
<p>The Big Apple!</p>
</div>
</InfoWindow>
)}
</GoogleMap>
</LoadScript>
);
}React Google Maps API is built around several key architectural components:
LoadScript, LoadScriptNext, useLoadScript, useJsApiLoader)GoogleMap container componentuseGoogleMap hookonLoad, onUnmount)Script loading utilities for initializing the Google Maps JavaScript API with various configuration options and loading strategies.
interface LoadScriptProps {
googleMapsApiKey: string;
libraries?: Libraries;
language?: string;
region?: string;
version?: string;
children?: React.ReactNode;
onLoad?: () => void;
onError?: (error: Error) => void;
}
function useLoadScript(options: UseLoadScriptOptions): {
isLoaded: boolean;
loadError: Error | undefined;
url: string;
};The main GoogleMap component that renders the interactive map container and manages the Google Maps instance.
interface GoogleMapProps {
children?: React.ReactNode;
id?: string;
mapContainerStyle?: React.CSSProperties;
mapContainerClassName?: string;
options?: google.maps.MapOptions;
center?: google.maps.LatLng | google.maps.LatLngLiteral;
zoom?: number;
onClick?: (e: google.maps.MapMouseEvent) => void;
onLoad?: (map: google.maps.Map) => void | Promise<void>;
onUnmount?: (map: google.maps.Map) => void | Promise<void>;
}
function GoogleMap(props: GoogleMapProps): JSX.Element;
function useGoogleMap(): google.maps.Map | null;Components for displaying markers, info windows, and custom overlay content positioned on the map.
interface MarkerProps {
position: google.maps.LatLng | google.maps.LatLngLiteral;
animation?: google.maps.Animation;
clickable?: boolean;
draggable?: boolean;
icon?: string | google.maps.Icon | google.maps.Symbol;
label?: string | google.maps.MarkerLabel;
onClick?: (e: google.maps.MapMouseEvent) => void;
onLoad?: (marker: google.maps.Marker) => void;
}
interface InfoWindowProps {
children?: React.ReactNode;
position?: google.maps.LatLng | google.maps.LatLngLiteral;
anchor?: google.maps.MVCObject;
options?: google.maps.InfoWindowOptions;
onCloseClick?: () => void;
}Components for creating and managing geometric shapes, drawing tools, and interactive drawing functionality on the map.
interface PolygonProps {
options?: google.maps.PolygonOptions;
path?: google.maps.LatLng[] | google.maps.LatLngLiteral[];
paths?: google.maps.LatLng[][] | google.maps.LatLngLiteral[][];
draggable?: boolean;
editable?: boolean;
onClick?: (e: google.maps.MapMouseEvent) => void;
onLoad?: (polygon: google.maps.Polygon) => void;
}
interface DrawingManagerProps {
options?: google.maps.drawing.DrawingManagerOptions;
drawingMode?: google.maps.drawing.OverlayType;
onOverlayComplete?: (e: google.maps.drawing.OverlayCompleteEvent) => void;
}Layer components for displaying additional information overlays like traffic, transit routes, and heatmaps.
interface TrafficLayerProps {
options?: google.maps.TrafficLayerOptions;
onLoad?: (trafficLayer: google.maps.TrafficLayer) => void;
}
interface HeatmapLayerProps {
data: google.maps.LatLng[] | google.maps.visualization.WeightedLocation[];
options?: google.maps.visualization.HeatmapLayerOptions;
onLoad?: (heatmapLayer: google.maps.visualization.HeatmapLayer) => void;
}Components for grouping nearby markers into clusters to improve performance and user experience with large marker datasets.
interface MarkerClustererProps {
children: React.ReactNode;
options?: ClustererOptions;
onLoad?: (clusterer: Clusterer) => void;
}
interface GoogleMarkerClustererProps {
children: React.ReactNode;
options?: google.maps.MarkerClustererOptions;
onLoad?: (clusterer: google.maps.MarkerClusterer) => void;
}Service components for accessing Google Maps platform services like directions, distance matrix, and Street View.
interface DirectionsServiceProps {
options: google.maps.DirectionsRequest;
callback: (
result: google.maps.DirectionsResult | null,
status: google.maps.DirectionsStatus
) => void;
onLoad?: (directionsService: google.maps.DirectionsService) => void;
}
interface DirectionsRendererProps {
directions?: google.maps.DirectionsResult;
options?: google.maps.DirectionsRendererOptions;
onLoad?: (directionsRenderer: google.maps.DirectionsRenderer) => void;
}Components for integrating Google Places API functionality, including autocomplete and place search capabilities.
interface AutocompleteProps {
children: React.ReactNode;
bounds?: google.maps.LatLngBounds | google.maps.LatLngBoundsLiteral;
restrictions?: google.maps.places.ComponentRestrictions;
fields?: string[];
options?: google.maps.places.AutocompleteOptions;
onPlaceChanged?: () => void;
onLoad?: (autocomplete: google.maps.places.Autocomplete) => void;
}
interface StandaloneSearchBoxProps {
children: React.ReactNode;
bounds?: google.maps.LatLngBounds | google.maps.LatLngBoundsLiteral;
options?: google.maps.places.SearchBoxOptions;
onPlacesChanged?: () => void;
}Before using React Google Maps API, ensure you have:
// Environment variables (recommended)
const API_KEY = process.env.REACT_APP_GOOGLE_MAPS_API_KEY;
// Conditional loading based on environment
function App() {
if (!API_KEY) {
return <div>Please configure Google Maps API key</div>;
}
return (
<LoadScript googleMapsApiKey={API_KEY}>
<GoogleMap /* ... */ />
</LoadScript>
);
}// Use LoadScript for entire app (recommended)
function App() {
return (
<LoadScript
googleMapsApiKey={API_KEY}
libraries={['places']} // Only load needed libraries
>
<Router>
<Routes>
<Route path="/map" element={<MapPage />} />
</Routes>
</Router>
</LoadScript>
);
}
// Alternative: useLoadScript for conditional loading
function MapComponent() {
const { isLoaded, loadError } = useLoadScript({
googleMapsApiKey: API_KEY,
libraries: ['places']
});
if (loadError) return <div>Error loading maps</div>;
if (!isLoaded) return <div>Loading maps...</div>;
return <GoogleMap /* ... */ />;
}function MapWithErrorHandling() {
const [mapError, setMapError] = useState<string | null>(null);
return (
<LoadScript
googleMapsApiKey={API_KEY}
onError={() => setMapError('Failed to load Google Maps API')}
>
{mapError ? (
<div>Error: {mapError}</div>
) : (
<GoogleMap
onLoad={(map) => console.log('Map loaded successfully')}
onUnmount={(map) => console.log('Map unmounted')}
/>
)}
</LoadScript>
);
}API Key Errors
Script Loading Issues
LoadScript, LoadScriptNext, or useLoadScript)Map Not Displaying
TypeScript Errors
@types/google.maps if not already presentgoogle.maps.LatLngPerformance Issues
libraries arrayReact.memo() for components that render many map elements// Old (react-google-maps)
import { GoogleMap, withGoogleMap, withScriptjs } from "react-google-maps";
// New (@react-google-maps/api)
import { GoogleMap, LoadScript } from "@react-google-maps/api";Key differences:
withGoogleMap, withScriptjs)LoadScript wrapperuseLoadScript and useGoogleMapThe package follows semantic versioning and maintains backward compatibility within major versions.