Polski

Tutorial · Google Maps · React

Google Maps in React – API key, Map ID, geolocation, place search, pins and cost control

A complete Google Maps integration for a React app with the official @vis.gl/react-google-maps library – from a restricted API key and a Map ID, through geolocation, address autocomplete (Places API New) and geocoding, to AdvancedMarker pins, info windows, clustering, fitting bounds and keeping costs under control.

By · · 27 min read

A map with pins looks like a one-afternoon feature: paste a script, add a key, done. Then the questions arrive: why did someone burn through our key's quota, why are the pins "deprecated", how do you show 400 points without freezing a phone, and where did the invoice come from when it "was supposed to be free". In this guide you'll build a restaurant finder for a dumpling shop chain in React and work through all of those topics one by one.

Prerequisites: a Google Cloud account with a billing account attached (required even within the free caps), Node.js 22+, React with hooks and TypeScript (see the React guide).

10,000
free map loads per month – Dynamic Maps SKU (Essentials)
3
APIs to enable – Maps JavaScript, Places (New), Geocoding
1
APIProvider – the API loads once for the whole app
400
clustered points – without janky scrolling

Step 1. Google Cloud: API key, restrictions and Map ID

  1. In the Google Cloud Console create a project and attach a billing account.
  2. In APIs & Services → Library enable Maps JavaScript API, Places API (New) and Geocoding API.
  3. In Keys & Credentials create an API key and restrict it straight away:

    • Application restrictions → Websites (HTTP referrers): list the addresses the key may be used from.
    • API restrictions → Restrict key: tick only the three APIs from step 2.
  4. In Map management create a JavaScript Map ID (vector, ideally). Without a Map ID, Advanced Markers and cloud-based map styling don't work. Locally you can start with DEMO_MAP_ID.
EnvironmentHTTP referrer restrictionNotes
localhttp://localhost:5173/*a separate development key with a low daily quota
staginghttps://staging.pierogarnia.example/*a separate key – easy to disable without touching production
productionhttps://pierogarnia.example/*, https://www.pierogarnia.example/*production domains only, daily quotas and a budget alert
Diagram: Everyone can see the key, but it only works from your domain and only for selected APIs

Step 2. Project and the first map

npm create vite@latest pierogi-maps -- --template react-ts
cd pierogi-maps
npm install @vis.gl/react-google-maps @googlemaps/markerclusterer zod
npm install -D @types/google.maps
cp .env.example .env.local   # put your key here

Configuration, environment variables and styles

package.json
{
  "name": "pierogi-maps",
  "private": true,
  "version": "0.1.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "tsc --noEmit && vite build",
    "preview": "vite preview"
  },
  "dependencies": {
    "@googlemaps/markerclusterer": "^2.6.2",
    "@vis.gl/react-google-maps": "^1.10.2",
    "react": "^19.3.1",
    "react-dom": "^19.3.1",
    "zod": "^4.6.7"
  },
  "devDependencies": {
    "@types/google.maps": "^3.67.0",
    "@types/react": "^19.3.0",
    "@types/react-dom": "^19.3.0",
    "@vitejs/plugin-react": "^6.3.0",
    "typescript": "~7.0.2",
    "vite": "^8.4.0"
  }
}
tsconfig.json
{
  "compilerOptions": {
    "target": "es2023",
    "lib": ["ES2023", "DOM", "DOM.Iterable"],
    "module": "esnext",
    "moduleResolution": "bundler",
    "types": ["vite/client", "google.maps"],
    "jsx": "react-jsx",
    "noEmit": true,
    "allowImportingTsExtensions": true,
    "verbatimModuleSyntax": true,
    "skipLibCheck": true,
    "noUncheckedIndexedAccess": true
  },
  "include": ["src", "vite.config.ts"]
}
vite.config.ts
import react from "@vitejs/plugin-react";
import { defineConfig } from "vite";

export default defineConfig({
  plugins: [react()],
});
.env.example
# Copy to .env.local (never commit it). The browser key is public by design –
# protect it with HTTP referrer + API restrictions in Google Cloud Console.
VITE_GOOGLE_MAPS_API_KEY=your-browser-key
# Map ID from "Map management" (needed for Advanced Markers). DEMO_MAP_ID works for local testing.
VITE_GOOGLE_MAPS_MAP_ID=DEMO_MAP_ID
src/env.d.ts
// Typed Vite env variables – a typo in the name becomes a compile error.
interface ImportMetaEnv {
  readonly VITE_GOOGLE_MAPS_API_KEY?: string;
  readonly VITE_GOOGLE_MAPS_MAP_ID?: string;
}

interface ImportMeta {
  readonly env: ImportMetaEnv;
}
src/config.ts
export const GOOGLE_MAPS_API_KEY = import.meta.env.VITE_GOOGLE_MAPS_API_KEY ?? "";
export const MAP_ID = import.meta.env.VITE_GOOGLE_MAPS_MAP_ID || "DEMO_MAP_ID";

// Tricity (Gdańsk–Sopot–Gdynia) – the default view before data arrives.
export const DEFAULT_CENTER: google.maps.LatLngLiteral = { lat: 54.43, lng: 18.57 };
index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Pierogarnia · Find us</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.tsx"></script>
  </body>
</html>
src/index.css
* { box-sizing: border-box; }
body { margin: 0; font-family: system-ui, sans-serif; color: #1f2328; }
.layout { display: grid; grid-template-columns: 340px 1fr; height: 100dvh; }
.sidebar { padding: 16px; overflow-y: auto; border-right: 1px solid #dee2e6; display: grid; gap: 12px; align-content: start; }
.map { position: relative; }
.list { list-style: none; margin: 0; padding: 0; display: grid; gap: 6px; }
.list button { width: 100%; text-align: left; padding: 8px 10px; border: 1px solid #dee2e6; border-radius: 8px; background: #fff; cursor: pointer; font: inherit; }
.list button[aria-current="true"] { border-color: #c2255c; background: #fff0f6; }
.muted { color: #6c757d; font-size: 0.875rem; }
.btn { padding: 8px 12px; border-radius: 8px; border: 1px solid #c2255c; background: #c2255c; color: #fff; cursor: pointer; font: inherit; }
.place-search gmp-place-autocomplete { width: 100%; }
.you-are-here { width: 18px; height: 18px; border-radius: 50%; background: #1971c2; border: 3px solid #fff; box-shadow: 0 0 0 0 rgba(25, 113, 194, 0.5); animation: pulse 2s infinite; }
@keyframes pulse { 70% { box-shadow: 0 0 0 14px rgba(25, 113, 194, 0); } 100% { box-shadow: 0 0 0 0 rgba(25, 113, 194, 0); } }
@media (prefers-reduced-motion: reduce) { .you-are-here { animation: none; } }
.info h3 { margin: 0 0 4px; font-size: 1rem; }
.info p { margin: 0; }
@media (max-width: 720px) { .layout { grid-template-columns: 1fr; grid-template-rows: auto 60dvh; } }

APIProvider loads the Maps JavaScript API once for the whole app. Extra libraries (marker, places, geocoding) load on demand when a component needs them. StoreMap is a thin wrapper around Map with our defaults:

APIProvider and the map component

src/main.tsx
import { APIProvider } from "@vis.gl/react-google-maps";
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App.tsx";
import { GOOGLE_MAPS_API_KEY } from "./config.ts";
import "./index.css";

const container = document.getElementById("root");
if (!container) throw new Error("#root element not found");

createRoot(container).render(
  <StrictMode>
    {/* Loads the Maps JavaScript API once; libraries (marker, places, geocoding) load on demand. */}
    <APIProvider
      apiKey={GOOGLE_MAPS_API_KEY}
      language="pl"
      region="PL"
      onError={(error) => console.error("Google Maps failed to load", error)}
    >
      <App />
    </APIProvider>
  </StrictMode>,
);
src/map/StoreMap.tsx
import { ColorScheme, Map, type MapProps } from "@vis.gl/react-google-maps";
import { DEFAULT_CENTER, MAP_ID } from "../config.ts";

// A thin wrapper with our defaults; children are markers, info windows and helpers.
export function StoreMap({ children, ...props }: MapProps) {
  return (
    <Map
      mapId={MAP_ID} // required for Advanced Markers and cloud-based styling
      defaultCenter={DEFAULT_CENTER}
      defaultZoom={11}
      gestureHandling="cooperative" // ctrl/two-finger zoom: the page still scrolls on mobile
      disableDefaultUI
      zoomControl
      fullscreenControl
      colorScheme={ColorScheme.FOLLOW_SYSTEM}
      reuseMaps // keep the map instance when the component remounts (fewer billed map loads)
      style={{ width: "100%", height: "100%" }}
      {...props}
    >
      {children}
    </Map>
  );
}
  • defaultCenter / defaultZoom are uncontrolled: the map starts there and the user moves it freely afterwards. If you pass center / zoom, the map becomes controlled, and without handling onCameraChanged it stops responding to dragging.
  • gestureHandling="cooperative" – on phones, scrolling the page doesn't get "trapped" in the map. The map pans with two fingers, and mouse-wheel zoom needs Ctrl.
  • colorScheme={ColorScheme.FOLLOW_SYSTEM} – a light or dark map following the OS setting (works with a Map ID).
  • reuseMaps – when the component remounts (e.g. navigating back), the library reuses the existing map instance instead of creating a new one. Every new instance is another billed map load.

Step 3. Restaurant data from an API

Restaurants come from an API (here: a static public/restaurants.json). We validate the response with a Zod schema, as in the TypeScript guide – broken coordinates shouldn't take the map down.

Data and the useRestaurants hook

public/restaurants.json
[
  { "id": "oliwa", "name": "Pierogarnia Oliwa", "district": "Gdańsk Oliwa", "lat": 54.4103, "lng": 18.5605, "open": "11:00–21:00", "delivery": true },
  { "id": "wrzeszcz", "name": "Pierogarnia Wrzeszcz", "district": "Gdańsk Wrzeszcz", "lat": 54.38, "lng": 18.606, "open": "11:00–22:00", "delivery": true },
  { "id": "glowne", "name": "Pierogarnia Główne Miasto", "district": "Gdańsk Główne Miasto", "lat": 54.3489, "lng": 18.6532, "open": "10:00–23:00", "delivery": false },
  { "id": "przymorze", "name": "Pierogarnia Przymorze", "district": "Gdańsk Przymorze", "lat": 54.404, "lng": 18.59, "open": "11:00–21:00", "delivery": true },
  { "id": "chelm", "name": "Pierogarnia Chełm", "district": "Gdańsk Chełm", "lat": 54.334, "lng": 18.618, "open": "12:00–20:00", "delivery": true },
  { "id": "zaspa", "name": "Pierogarnia Zaspa", "district": "Gdańsk Zaspa", "lat": 54.3995, "lng": 18.6045, "open": "11:00–21:00", "delivery": false },
  { "id": "sopot", "name": "Pierogarnia Sopot", "district": "Sopot Centrum", "lat": 54.4445, "lng": 18.5665, "open": "10:00–24:00", "delivery": false },
  { "id": "orlowo", "name": "Pierogarnia Orłowo", "district": "Gdynia Orłowo", "lat": 54.48, "lng": 18.563, "open": "11:00–21:00", "delivery": true },
  { "id": "gdynia", "name": "Pierogarnia Gdynia Centrum", "district": "Gdynia Śródmieście", "lat": 54.5189, "lng": 18.5305, "open": "10:00–22:00", "delivery": true },
  { "id": "chylonia", "name": "Pierogarnia Chylonia", "district": "Gdynia Chylonia", "lat": 54.544, "lng": 18.46, "open": "11:00–20:00", "delivery": true },
  { "id": "rumia", "name": "Pierogarnia Rumia", "district": "Rumia", "lat": 54.571, "lng": 18.39, "open": "11:00–20:00", "delivery": false },
  { "id": "pruszcz", "name": "Pierogarnia Pruszcz", "district": "Pruszcz Gdański", "lat": 54.262, "lng": 18.636, "open": "11:00–20:00", "delivery": true }
]
src/api/restaurants.ts
import { useEffect, useState } from "react";
import { z } from "zod";

const RestaurantSchema = z.object({
  id: z.string(),
  name: z.string(),
  district: z.string(),
  lat: z.number().min(-90).max(90),
  lng: z.number().min(-180).max(180),
  open: z.string(),
  delivery: z.boolean(),
});
export type Restaurant = z.infer<typeof RestaurantSchema>;

export const positionOf = (r: Restaurant): google.maps.LatLngLiteral => ({ lat: r.lat, lng: r.lng });

type State = { status: "loading" } | { status: "error"; message: string } | { status: "ready"; restaurants: Restaurant[] };

// In a real app this is GET /api/restaurants (or a TanStack Query hook) – the map does not care.
export function useRestaurants(): State {
  const [state, setState] = useState<State>({ status: "loading" });

  useEffect(() => {
    const controller = new AbortController();
    fetch("/restaurants.json", { signal: controller.signal })
      .then((res) => (res.ok ? res.json() : Promise.reject(new Error(`HTTP ${res.status}`))))
      .then((json: unknown) => setState({ status: "ready", restaurants: z.array(RestaurantSchema).parse(json) }))
      .catch((e: unknown) => {
        if (!controller.signal.aborted) setState({ status: "error", message: e instanceof Error ? e.message : String(e) });
      });
    return () => controller.abort();
  }, []);

  return state;
}

The rest of this article is for members

Create a free account or sign in to read it all. Still ahead:

  • Step 4. Pins: AdvancedMarker, Pin and InfoWindow
  • Step 5. Geolocation and a custom HTML marker
  • Step 6. Address search and geocoding
  • Step 7. Camera: fitting bounds and panning
  • Step 8. Many markers and clustering
  • Step 9. Putting the app together
  • Performance with thousands of points
  • Cost control
  • Common mistakes
  • Check yourself
  • What next

Create a free account · Sign in