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

Claude Code से Geolocation API सुरक्षित बनाना: permissions, fallback और tests

Claude Code से Geolocation API सुरक्षित बनाएं: permissions, HTTPS, fallback, privacy और tests.

Claude Code से Geolocation API सुरक्षित बनाना: permissions, fallback और tests

Location feature दिखने में छोटा होता है, लेकिन production में यह sensitive flow बन जाता है। Nearby store search, delivery availability, field check-in या local content में browser permission, HTTPS, timeout, manual fallback, map provider boundary, privacy-safe logging और mocked tests सभी जरूरी हैं।

अगर Claude Code से सिर्फ “current location button बनाओ” कहा जाए, तो वह getCurrentPosition call कर सकता है और coordinates दिखा सकता है। लेकिन अच्छी implementation में user को पहले वजह बताई जाती है, permission सिर्फ click के बाद मांगी जाती है, deny या timeout पर postcode/address input मिलता है, और raw latitude/longitude logs में नहीं जाते।

Primary references: MDN Geolocation API, getCurrentPosition, watchPosition, Permissions API, W3C Geolocation specification, Chrome secure origins, Chrome DevTools Sensors, Playwright emulation, और Claude Code permissions। Related reading: map integration, security audit, और responsive design.

पहले boundary तय करें

Geolocation API browser से device की estimated location मांगती है। Browser GPS, Wi-Fi, cell tower, IP, OS location service या cached data use कर सकता है। Web app यह source choose नहीं करता और result हमेशा exact नहीं होता।

Implementation से पहले चार decisions लें। Permission page load पर नहीं, user action के बाद मांगें। Default में enableHighAccuracy: false रखें। Failure पर postcode, city या address input दें। Raw coordinates store करने की जरूरत सच में है या नहीं, यह पहले तय करें।

DecisionRecommended defaultCommon mistake
Permission timingButton click के बादPage open होते ही prompt
AccuracyHigh accuracy offहर use case में GPS जैसा precision
FallbackPostcode/address inputDeny होने पर flow बंद
LogsEvents और coarse bucketsposition.coords को analytics में भेजना

Map layer अलग रखें। Geolocation सिर्फ coordinates देती है। Map render, geocoding, route calculation और nearby places search Google Maps, Mapbox, OpenStreetMap या backend का काम है।

Real product use cases

पहला use case store locator है। User “use my location” click करता है और app nearby stores sort करती है। उसी screen पर postcode search भी होना चाहिए ताकि privacy-conscious user purchase flow छोड़कर न जाए।

दूसरा use case delivery या home service availability है। Grocery, repair, rental और appointment services user की location से service zone और time slot दिखा सकती हैं। Server को exact coordinates की जगह inside_zone या distance bucket ही चाहिए हो सकता है।

तीसरा use case field check-in है। Cleaning, maintenance, event staff और sales visit में location से site proximity confirm हो सकती है। लेकिन device failure पर काम रुकना नहीं चाहिए; photo, supervisor approval या manual note fallback रखें।

चौथा use case local content है। Weather, local events, stock, city notices location से बेहतर हो सकते हैं। अगर city-level result काफी है, तो saved city preference precise live location से बेहतर है।

getCurrentPosition का runnable example

इसे geo-demo.html के रूप में save करें और localhost या HTTPS से चलाएं। Plain HTTP पर modern browsers Geolocation block कर सकते हैं।

<!doctype html>
<html lang="hi">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Geolocation demo</title>
    <style>
      body {
        font-family: system-ui, sans-serif;
        line-height: 1.6;
        margin: 2rem;
      }
      button,
      input {
        font: inherit;
        padding: 0.7rem 0.9rem;
      }
      .panel {
        border: 1px solid #ddd;
        max-width: 36rem;
        padding: 1rem;
      }
    </style>
  </head>
  <body>
    <main class="panel">
      <h1>Nearby stores खोजें</h1>
      <p>
        Location सिर्फ stores sort करने के लिए use होगी।
        Exact address या movement history save नहीं होगी।
      </p>

      <button id="useLocation" type="button">मेरी location use करें</button>
      <p id="status" role="status" aria-live="polite"></p>
      <pre id="result"></pre>

      <form id="manualForm">
        <label for="postcode">Postcode, city या address</label>
        <input id="postcode" name="postcode" autocomplete="postal-code" />
        <button type="submit">Manual search</button>
      </form>
    </main>

    <script type="module">
      const status = document.querySelector("#status");
      const result = document.querySelector("#result");
      const button = document.querySelector("#useLocation");
      const form = document.querySelector("#manualForm");

      function showManual(reason) {
        status.textContent =
          `${reason}. आप postcode या city से भी search कर सकते हैं।`;
      }

      function onSuccess(position) {
        const { latitude, longitude, accuracy } = position.coords;
        status.textContent = "Location मिल गई।";
        result.textContent = JSON.stringify(
          {
            lat: Number(latitude.toFixed(5)),
            lng: Number(longitude.toFixed(5)),
            accuracyMeters: Math.round(accuracy),
          },
          null,
          2,
        );
      }

      function onError(error) {
        const messages = {
          1: "Location permission deny हो गई",
          2: "Device location available नहीं है",
          3: "Location request timeout हो गई",
        };
        showManual(messages[error.code] ?? "Location unavailable है");
      }

      button.addEventListener("click", () => {
        if (!("geolocation" in navigator)) {
          showManual("यह browser Geolocation support नहीं करता");
          return;
        }

        status.textContent = "Location permission check हो रही है...";
        navigator.geolocation.getCurrentPosition(onSuccess, onError, {
          enableHighAccuracy: false,
          timeout: 8000,
          maximumAge: 60000,
        });
      });

      form.addEventListener("submit", (event) => {
        event.preventDefault();
        const data = new FormData(form);
        status.textContent =
          `"${data.get("postcode")}" के आसपास search होगा।`;
      });
    </script>
  </body>
</html>

timeout wait limit है। maximumAge recent cached location allow करता है। enableHighAccuracy higher precision request करता है, लेकिन यह slow और battery-heavy हो सकता है।

watchPosition को साफ रोकें

watchPosition repeated updates देता है। यह delivery route या active field task के लिए ठीक है, simple store search के लिए नहीं। Returned ID को clearWatch से stop करें।

import { useEffect, useRef, useState } from "react";

type LocationPoint = {
  lat: number;
  lng: number;
  accuracy: number;
  at: string;
};

export function TrackingPanel() {
  const watchId = useRef<number | null>(null);
  const [points, setPoints] = useState<LocationPoint[]>([]);
  const [error, setError] = useState<string | null>(null);

  function start() {
    if (!navigator.geolocation || watchId.current !== null) return;

    watchId.current = navigator.geolocation.watchPosition(
      (position) => {
        const { latitude, longitude, accuracy } = position.coords;
        setPoints((current) => [
          {
            lat: Number(latitude.toFixed(5)),
            lng: Number(longitude.toFixed(5)),
            accuracy: Math.round(accuracy),
            at: new Date(position.timestamp).toISOString(),
          },
          ...current.slice(0, 9),
        ]);
      },
      (err) => setError(`Tracking failed: ${err.code}`),
      {
        enableHighAccuracy: true,
        timeout: 10000,
        maximumAge: 5000,
      },
    );
  }

  function stop() {
    if (watchId.current === null) return;
    navigator.geolocation.clearWatch(watchId.current);
    watchId.current = null;
  }

  useEffect(() => stop, []);

  return (
    <section>
      <button type="button" onClick={start}>Tracking start</button>
      <button type="button" onClick={stop}>Stop</button>
      {error && <p role="alert">{error}</p>}
      <ol>
        {points.map((point) => (
          <li key={point.at}>
            {point.lat}, {point.lng}
            {" / "}
            {point.accuracy}m
          </li>
        ))}
      </ol>
    </section>
  );
}

Tracking product में start, pause और finish clearly visible होने चाहिए। Data retention, internal access और deletion policy भी code से पहले तय करें।

Privacy-safe logging

Latitude और longitude को normal debug log न मानें। वे monitoring, analytics, support screenshots और session replay में फैल सकते हैं। Events और coarse buckets बेहतर हैं।

type GeoLogInput = {
  lat: number;
  lng: number;
  accuracy: number;
  permission: "granted" | "prompt" | "denied" | "unknown";
};

export function toPrivacySafeGeoLog(input: GeoLogInput) {
  return {
    permission: input.permission,
    accuracyBucket:
      input.accuracy <= 50 ? "high" :
      input.accuracy <= 500 ? "medium" : "low",
    latBucket: Number(input.lat.toFixed(2)),
    lngBucket: Number(input.lng.toFixed(2)),
  };
}

Conversion analysis में permission_denied, manual_search_used, timeout और results_shown जैसे events अक्सर काफी हैं। Claude Code prompt में “raw latitude/longitude log मत करना” जरूर लिखें।

Permissions API state पढ़ सकती है, लेकिन actual permission dialog Geolocation call पर ही आता है।

export async function readGeoPermission() {
  if (!("permissions" in navigator)) return "unknown";

  try {
    const status = await navigator.permissions.query({
      name: "geolocation",
    });
    return status.state;
  } catch {
    return "unknown";
  }
}

Failure modes और tests

HTTPS test करें। Modern browsers secure context मांगते हैं, और iframe में Permissions-Policy Geolocation block कर सकता है।

Permission denied test करें। UI को manual address/postcode fallback दिखाना चाहिए, repeated prompt नहीं।

Timeout और unavailable location test करें। Indoor device, desktop, VPN, OS location off और enterprise policy failures पैदा कर सकते हैं।

Cache test करें। maximumAge fast UX देता है, लेकिन check-in में पुरानी location गलत हो सकती है।

import { expect, test } from "@playwright/test";

test.use({
  geolocation: {
    latitude: 28.613939,
    longitude: 77.209023,
    accuracy: 50,
  },
  permissions: ["geolocation"],
});

test("shows nearby stores from mocked location", async ({ page }) => {
  await page.goto("/stores");
  await page.getByRole("button", { name: "मेरी location use करें" }).click();
  await expect(page.getByText("Location मिल गई")).toBeVisible();
});

Safe Claude Code prompt

Prompt में scope, no-go areas और verification साफ लिखें।

claude <<'PROMPT'
Implement a beginner-friendly Geolocation feature.

Scope:
- Edit only src/features/location and related tests.
- Do not change billing, analytics, or map provider config.
- Preserve existing API keys and environment variable names.

Requirements:
- Request location only after the user clicks a button.
- Explain why location is needed before the browser prompt.
- Use getCurrentPosition with timeout and maximumAge.
- Add manual postcode/address fallback for denied or timeout cases.
- Do not log raw latitude or longitude.
- Add a Playwright test with mocked geolocation.
- Return a short verification checklist.
PROMPT

Team workflow में .env read और automatic push को deny करें, test और lint commands allow करें।

{
  "permissions": {
    "deny": [
      "Read(./.env)",
      "Read(./.env.*)",
      "Bash(git push *)"
    ],
    "allow": [
      "Bash(npm test *)",
      "Bash(npm run lint)"
    ]
  }
}

अगर आपकी team को location feature, map provider, privacy rules और tests को reusable standard बनाना है, तो Claude Code training and consultation practical next step है।

Hands-on verification note

Examples को Chrome localhost पर run करके, DevTools Sensors में Delhi और “Location unavailable” से check किया। Playwright example ने granted permission success path verify किया। Production से पहले OS location off, enterprise browser policy, iframe permissions, denied permission, map provider quota और raw coordinate logs की scan जरूर करें।

#Claude Code #Geolocation #location #map #Web API
मुफ़्त

मुफ़्त PDF: Claude Code cheatsheet

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

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

Masa

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

Masa

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