or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

clustering.mdcore-map.mddrawing-shapes.mdindex.mdlayers.mdmarkers-overlays.mdplaces.mdscript-loading.mdservices.md
tile.json

tessl/npm-react-google-maps--api

React.js Google Maps API integration with components and hooks for seamless Google Maps functionality

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@react-google-maps/api@2.20.x

To install, run

npx @tessl/cli install tessl/npm-react-google-maps--api@2.20.0

index.mddocs/

React Google Maps API

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.

Package Information

  • Package Name: @react-google-maps/api
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install @react-google-maps/api

Core Imports

import { 
  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");

Basic Usage

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>
  );
}

Architecture

React Google Maps API is built around several key architectural components:

  • Script Loading System: Multiple approaches for loading Google Maps JavaScript API (LoadScript, LoadScriptNext, useLoadScript, useJsApiLoader)
  • Component Hierarchy: All map components must be rendered within a GoogleMap container component
  • Context System: Map instance is provided through React Context, accessible via useGoogleMap hook
  • Event-Driven Design: Extensive event handling system with lifecycle callbacks (onLoad, onUnmount)
  • Type Safety: Full TypeScript support with detailed interfaces for all Google Maps API types
  • Functional Variants: Many components offer both class-based and functional hook-based implementations (with 'F' suffix)

Capabilities

Script Loading & Initialization

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;
};

Script Loading

Core Map Component

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;

Core Map

Markers & Overlays

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;
}

Markers & Overlays

Drawing & Shapes

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;
}

Drawing & Shapes

Map Layers

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;
}

Layers

Marker Clustering

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;
}

Clustering

Google Maps Services

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;
}

Services

Places Integration

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;
}

Places

Prerequisites

Before using React Google Maps API, ensure you have:

  • Google Maps JavaScript API Key: Required for loading the Google Maps API
    • Create an API key in Google Cloud Console
    • Enable Google Maps JavaScript API
    • (Optional) Enable additional APIs: Places API, Directions API, Distance Matrix API
  • React Application: Compatible with React 16.8+ (hooks support required)
  • TypeScript Support: Package includes full TypeScript definitions
  • Internet Connection: Required for loading Google Maps API scripts

Common Patterns

API Key Management

// 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>
  );
}

Performance Optimization

// 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 /* ... */ />;
}

Error Handling

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>
  );
}

Troubleshooting

Common Issues

API Key Errors

  • Ensure API key is valid and has proper permissions
  • Check that Google Maps JavaScript API is enabled
  • Verify billing is enabled for your Google Cloud project
  • Add your domain to API key restrictions if using referrer restrictions

Script Loading Issues

  • Use only one script loading method (LoadScript, LoadScriptNext, or useLoadScript)
  • Avoid multiple LoadScript instances in the same application
  • Check browser console for network errors or CSP violations

Map Not Displaying

  • Ensure map container has explicit dimensions (width/height)
  • Verify the map center coordinates are valid
  • Check that the Google Maps API has finished loading before rendering

TypeScript Errors

  • Install @types/google.maps if not already present
  • Ensure you're importing types correctly: google.maps.LatLng
  • Use the provided interfaces from this package for component props

Performance Issues

  • Limit the number of markers rendered simultaneously (use clustering)
  • Load only necessary libraries in the libraries array
  • Use React.memo() for components that render many map elements
  • Implement virtual scrolling for large datasets

Migration from react-google-maps

// 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:

  • No HOCs required (withGoogleMap, withScriptjs)
  • Direct component usage with LoadScript wrapper
  • Improved TypeScript support
  • Better tree-shaking and smaller bundle size
  • Hook-based API with useLoadScript and useGoogleMap

Version Compatibility

  • React: 16.8+ (hooks required), 17.x, 18.x, 19.x supported
  • Google Maps API: Weekly, quarterly, and versioned releases supported
  • TypeScript: 4.0+ recommended for full type support
  • Node.js: 14+ for development builds

The package follows semantic versioning and maintains backward compatibility within major versions.