Use Cases (अपडेट: 2/6/2026)

Claude Code से Google Maps को Next.js Web App में जोड़ने की practical guide

Claude Code से Google Maps जोड़ें: Advanced Markers, geocoding, store locator, Mapbox और production checks।

Claude Code से Google Maps को Next.js Web App में जोड़ने की practical guide

Map दिखाने से पहले feature design करें

Claude Code से आप जल्दी से Google Maps component बनवा सकते हैं, लेकिन production quality सिर्फ map दिखाने से नहीं आती। असली काम है API key को restrict करना, billing alert लगाना, address search को server और browser में सही जगह बाँटना, mobile layout संभालना, privacy समझना और error states लिखना।

Masa ने store locator prototype में जो गलती देखी, वह marker से जुड़ी नहीं थी। दिक्कत address search में आई। Geocoding का मतलब है address को latitude और longitude में बदलना। यह simple API call लगती है, लेकिन एक address कई जगहों से match हो सकता है, हर request cost बना सकती है, और result को store या display करने के नियम provider policy पर depend करते हैं।

इस लेख में हम Claude Code को snippet generator नहीं, बल्कि implementation partner की तरह इस्तेमाल करेंगे। Example stack है Next.js App Router, React, Google Maps JavaScript API, Advanced Markers, Geocoding API और जरूरत पड़ने पर Mapbox GL JS। API key और permission के लिए Claude Code security audit, speed के लिए performance optimization, और geo data के लिए data visualization भी पढ़ें।

Claude Code को साफ brief दें

Prompt में सिर्फ “Google Maps जोड़ो” न लिखें। Operating constraints लिखें, ताकि Claude Code demo code की जगह production के करीब implementation दे।

Next.js App Router में store locator page implement करें।

Requirements:
- Google Maps JavaScript API use करें
- पुराने Marker की जगह AdvancedMarkerElement use करें
- browser key NEXT_PUBLIC_GOOGLE_MAPS_API_KEY से पढ़ें
- HTTP referrer restriction और API restriction को मानकर चलें
- Geocoding API server route से call करें और GOOGLE_MAPS_SERVER_KEY use करें
- server key browser bundle में न जाए
- address search, store list, marker click और selected state sync रहें
- SSR के दौरान window या google read न करें
- loading, error, empty, location permission denied और mobile states handle करें
- अंत में API restrictions, budget alerts और policy checklist दें

Architecture को छोटे हिस्सों में बाँटें।

flowchart LR
  User["User"]
  Page["Store locator page"]
  Map["Google Maps JS API"]
  Route["/api/geocode"]
  Google["Geocoding API"]
  Store["Store data"]
  Alerts["Billing alerts and logs"]

  User --> Page
  Page --> Map
  Page --> Store
  Page --> Route
  Route --> Google
  Route --> Alerts

टीम review में terms को सरल रखें। Geocoding यानी address को coordinates में बदलना। Reverse geocoding यानी coordinates से likely address निकालना। Map ID यानी Google Cloud में बना identifier जो styled maps और Advanced Markers के लिए use होता है।

Next.js में Google Maps safely load करें

Loader और types install करें। Types पुराने examples पकड़ने में मदद करते हैं।

npm i @googlemaps/js-api-loader
npm i -D @types/google.maps

Advanced Markers के लिए map ID चाहिए। Local test मेंDEMO_MAP_IDचल सकता है, लेकिन production में Google Cloud Console से बना map ID use करें। Browser key Maps JavaScript API में visible होगी; इसलिए Google Maps Platform security guidance के अनुसार HTTP referrer restriction और API restriction जरूरी हैं।

// src/lib/google-maps-loader.ts
import { Loader } from "@googlemaps/js-api-loader";

let googleMapsPromise: Promise<typeof google> | null = null;

export function loadGoogleMaps() {
  const apiKey = process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY;

  if (!apiKey) {
    throw new Error("NEXT_PUBLIC_GOOGLE_MAPS_API_KEY is missing");
  }

  if (!googleMapsPromise) {
    const loader = new Loader({
      apiKey,
      version: "weekly",
      libraries: ["marker", "places"],
    });

    googleMapsPromise = loader.load();
  }

  return googleMapsPromise;
}

Map component client-side होना चाहिए। API कोuseEffectके अंदर load करें, ताकि SSR मेंgoogle is not definedन आए। Marker cleanup भी जरूरी है।

// src/components/GoogleBusinessMap.tsx
"use client";

import { useEffect, useRef } from "react";
import { loadGoogleMaps } from "@/lib/google-maps-loader";

export type MapPoint = {
  id: string;
  title: string;
  lat: number;
  lng: number;
  category?: "store" | "warehouse" | "property";
};

type Props = {
  points: MapPoint[];
  center: google.maps.LatLngLiteral;
  zoom?: number;
  onSelect?: (point: MapPoint) => void;
};

export function GoogleBusinessMap({ points, center, zoom = 13, onSelect }: Props) {
  const mapRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    let cancelled = false;
    let markers: google.maps.marker.AdvancedMarkerElement[] = [];

    async function renderMap() {
      await loadGoogleMaps();
      if (!mapRef.current || cancelled) return;

      const { Map } = (await google.maps.importLibrary("maps")) as google.maps.MapsLibrary;
      const { AdvancedMarkerElement, PinElement } = (await google.maps.importLibrary(
        "marker",
      )) as google.maps.MarkerLibrary;

      const map = new Map(mapRef.current, {
        center,
        zoom,
        mapId: process.env.NEXT_PUBLIC_GOOGLE_MAPS_MAP_ID ?? "DEMO_MAP_ID",
        fullscreenControl: false,
        gestureHandling: "cooperative",
      });

      markers = points.map((point, index) => {
        const pin = new PinElement({
          glyph: String(index + 1),
          background: point.category === "warehouse" ? "#0f766e" : "#2563eb",
          borderColor: "#ffffff",
          glyphColor: "#ffffff",
        });

        const marker = new AdvancedMarkerElement({
          map,
          position: { lat: point.lat, lng: point.lng },
          title: point.title,
          content: pin.element,
        });

        marker.addListener("click", () => onSelect?.(point));
        return marker;
      });
    }

    renderMap().catch((error) => console.error("Failed to render Google Map", error));

    return () => {
      cancelled = true;
      markers.forEach((marker) => {
        marker.map = null;
      });
    };
  }, [center.lat, center.lng, points, zoom, onSelect]);

  return <div ref={mapRef} className="h-[420px] w-full rounded-lg border" />;
}

User input को HTML string बनाकर InfoWindow में न डालें। Store name और address CMS या admin panel से आ सकते हैं, इसलिए उन्हें text की तरह render करें।

Geocoding को server route में रखें

Browser key और server key अलग रखें। Browser key referrer से restricted होनी चाहिए। Server key को deployment environment के हिसाब से restrict करें। Status और response format के लिए official Geocoding request and response देखें।

// src/app/api/geocode/route.ts
import { NextResponse } from "next/server";

type GeocodeResponse = {
  status: string;
  error_message?: string;
  results: Array<{
    formatted_address: string;
    place_id: string;
    geometry: { location: { lat: number; lng: number } };
  }>;
};

const endpoint = "https://maps.googleapis.com/maps/api/geocode/json";

export async function GET(request: Request) {
  const key = process.env.GOOGLE_MAPS_SERVER_KEY;
  const { searchParams } = new URL(request.url);
  const address = searchParams.get("address")?.trim();

  if (!key) return NextResponse.json({ error: "Server key is missing" }, { status: 500 });
  if (!address || address.length > 180) {
    return NextResponse.json({ error: "Address is required" }, { status: 400 });
  }

  const params = new URLSearchParams({ address, key, language: "hi", region: "in" });
  const response = await fetch(`${endpoint}?${params}`, { cache: "no-store" });
  const data = (await response.json()) as GeocodeResponse;
  const first = data.results[0];

  if (!response.ok || data.status !== "OK" || !first) {
    return NextResponse.json(
      { error: data.error_message ?? data.status },
      { status: data.status === "ZERO_RESULTS" ? 404 : 502 },
    );
  }

  return NextResponse.json({
    formattedAddress: first.formatted_address,
    placeId: first.place_id,
    location: first.geometry.location,
  });
}

सिर्फ cost बचाने के लिए long cache न लगाएँ। Geocoding result को कितनी देर store किया जा सकता है, यह Google Maps Platform terms और product policy पर निर्भर करता है। Store की official coordinates को अपने database में रखें; user search को minimum necessary data की तरह handle करें।

Practical use cases

पहला use case store locator है: branches, clinics, classes, showrooms या event venues। इसमें address search, current location, hours, phone और booking CTA चाहिए। Masa के prototype में mobile पर map बहुत बड़ा था और list नीचे दब गई। बेहतर pattern था list पहले दिखाना और user select करे तो map center बदलना।

दूसरा use case real estate या lodging search है। Price, availability, size, walking distance, filters और map bounds sync रहने चाहिए। सभी markers एक साथ render करना अच्छा नहीं है। Claude Code को कहें कि current viewport के results ही load करे, dense area cluster करे और visible map के हिसाब से list रखे।

तीसरा use case delivery, field sales या maintenance dashboard है। यहाँ map decoration नहीं, operations surface है। Location update frequency, access control, retention period और permission denied behavior पहले तय करें। Route optimization जोड़ने से पहले Routes API या Directions API cost model देखें।

चौथा use case editorial map है: travel guide, local guide, event report। Map exploration बढ़ाता है, पर useful text को replace नहीं करता। Directions, local context, accessibility notes और decision criteria article body में रहने चाहिए।

Mapbox कब चुनें

Google Maps store search, address search, Places data और familiar UX के लिए अच्छा है। Mapbox GL JS तब बेहतर होता है जब आपके पास अपना geo dataset हो, custom cartography चाहिए या WebGL layers जरूरी हों। Basic concepts के लिए Mapbox GL JS guides देखें।

CriteriaGoogle MapsMapbox GL JS
Store locatorGeocoding और Places के साथ strongOwn data हो तो अच्छा
Visual controlCloud Styling काफी हो सकता हैStyle और layer control ज्यादा
Learning costCommon apps के लिए आसानsource, layer, style समझना पड़ता है
Operationskey restriction और billing alerttoken restriction और attribution
// src/components/MapboxPreview.tsx
"use client";

import { useEffect, useRef } from "react";
import mapboxgl from "mapbox-gl";
import "mapbox-gl/dist/mapbox-gl.css";

export function MapboxPreview() {
  const containerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const token = process.env.NEXT_PUBLIC_MAPBOX_TOKEN;
    if (!containerRef.current || !token) return;

    mapboxgl.accessToken = token;

    const map = new mapboxgl.Map({
      container: containerRef.current,
      style: "mapbox://styles/mapbox/streets-v12",
      center: [77.209, 28.6139],
      zoom: 12,
    });

    map.addControl(new mapboxgl.NavigationControl(), "top-right");
    return () => map.remove();
  }, []);

  return <div ref={containerRef} className="h-[420px] w-full rounded-lg border" />;
}

Claude Code को “दोनों बना दो” कहने के बजाय roles split करें: address search और store discovery के लिए Google Maps, custom data layer के लिए Mapbox।

Production pitfalls

पहला pitfall unrestricted API key है। Browser key visible होगी, लेकिन referrer और API restriction जरूरी है। Server key कभी browser bundle में नहीं जानी चाहिए।

दूसरा pitfall पुरानाMarkerexample है। Google अब Advanced Markers recommend करता है; official Advanced Markers guide मेंAdvancedMarkerElementflow है।

तीसरा pitfall SSR है। Next.js file के top level परgoogle.maps.Mapलिखने सेgoogle is not definedआता है। Map को client component रखें और APIuseEffectमें load करें।

चौथा pitfall ambiguous address है। छोटे place names या station names कई results दे सकते हैं। language, region, country, structured input या candidate selection use करें। Raw address को database key न बनाएँ।

पाँचवां pitfall performance है। बहुत सारे markers और list cards page को slow करते हैं। Data बड़ा हो तो clustering, viewport query, pagination या server search use करें।

छठा pitfall privacy है। Current location के लिए user permission चाहिए। Deny होने पर UI टूटना नहीं चाहिए; location store करते हैं तो purpose और retention स्पष्ट होना चाहिए।

Summary और verification note

Claude Code से Google Maps integrate करते समय map rendering, geocoding, key management, billing, privacy और mobile UX को अलग-अलग जिम्मेदारी की तरह संभालें। Google Maps address और store workflows में मजबूत है; Mapbox custom data layers और visual control में मजबूत है।

इस update में real API key के बिना verify हो सकने वाले हिस्से देखे गए: Next.js responsibility split, SSR-safe loading, error branches और code fence format। Real key लगाने से पहले Google Cloud Console में Maps JavaScript API, Geocoding API, HTTP referrer restriction, server key restriction और budget alerts set करें। पहले 3 stores से search, marker click, mobile layout और billing metrics check करें, फिर production data जोड़ें।

#Claude Code #Google Maps #Mapbox #maps #geolocation
मुफ़्त

मुफ़्त PDF: Claude Code cheatsheet

Email डालें और commands, review habits तथा safe workflow वाली एक-page PDF पाएँ.

हम आपका data सुरक्षित रखते हैं और spam नहीं भेजते.

Masa

लेखक के बारे में

Masa

Claude Code workflow और team adoption पर काम करने वाला engineer.