Geolocation Integration Guide
Technology: geolocation · Category: tooling · Last reviewed: 2026-10-20
Source: https://tech-stack.codeamanilabs.org/guide/geolocation
Insight:
Location comes from three very different places — the device (GPS-precise, but consent- and HTTPS-gated, foreground-only), the edge (Vercel/Cloudflare stamp a city-level guess from the IP onto every request, free and silent), and a geocoding provider (turns pins into addresses and back, billed per SKU since Google retired the $200 credit in March 2025). The hard part isn't the API, it's the law: a stored lat/lng accurate to ~1,750–1,850 ft is "precise geolocation", which California treats as sensitive personal information and Virginia/Oregon forbid selling. codeAmani defaults from the IP, asks for the precise signal only when a feature needs it, rounds before storing, and never sells or shares it.
██████╗ ███████╗ ██████╗ ██╗ ██████╗ ██████╗ █████╗ ████████╗██╗ ██████╗ ███╗ ██╗
██╔════╝ ██╔════╝██╔═══██╗██║ ██╔═══██╗██╔════╝██╔══██╗╚══██╔══╝██║██╔═══██╗████╗ ██║
██║ ███╗█████╗ ██║ ██║██║ ██║ ██║██║ ███████║ ██║ ██║██║ ██║██╔██╗ ██║
██║ ██║██╔══╝ ██║ ██║██║ ██║ ██║██║ ██╔══██║ ██║ ██║██║ ██║██║╚██╗██║
╚██████╔╝███████╗╚██████╔╝███████╗╚██████╔╝╚██████╗██║ ██║ ██║ ██║╚██████╔╝██║ ╚████║
╚═════╝ ╚══════╝ ╚═════╝ ╚══════╝ ╚═════╝ ╚═════╝╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝
Geolocation Integration Guide
Focus: know where a user is with the least precision the feature needs — default from the request IP at the edge, ask the browser for a GPS fix only with explicit, revocable consent, turn coordinates into addresses server-side, and treat every stored lat/lng as sensitive personal data under US state privacy law (and KDPA 2019 on Kenya-targeted projects).
Overview
There are three sources of "where", at opposite ends of the precision/consent spectrum:
| Source | How | Precision | Consent | Cost |
|---|---|---|---|---|
Device (navigator.geolocation) |
GPS / Wi-Fi / cell, in the browser | metres | Browser prompt, HTTPS only, revocable | Free; battery |
| Edge IP geo | Vercel geolocation(request) / x-vercel-ip-*; Cloudflare request.cf |
city (often wrong on mobile/VPN) | None (but the IP is still personal data) | Free, zero extra calls |
| Geocoding / Places provider | Google Maps Platform, Mapbox, Nominatim — server-side | address ↔ point | n/a (you send it data you already hold) | Per-request, per-SKU |
A good product renders immediately from the IP default, asks for the precise signal from a user gesture only when the feature needs it (map pin, nearest store, live delivery), and degrades gracefully when permission is denied.
Hard truths that shape every integration:
- Consent is mandatory and revocable. The first
getCurrentPosition/watchPositioncall triggers the browser prompt. Users can deny, or grant then revoke in site settings. Handlegranted/denied/prompt, and the Permissionschangeevent mid-session. - Secure context only.
navigator.geolocationworks only over HTTPS (localhostcounts). Cross-origin iframes also needallow="geolocation"— thegeolocationPermissions-Policy default allowlist isself. - Foreground only. The web API has no background location and no native geofence. Updates stop when the tab is hidden.
- A
watchPositionyou don't clear is a battery leak.clearWatchin the React effect cleanup — non-negotiable. - Precise location is sensitive data in the US. See Privacy & compliance.
Official Documentation
| Source | URL | What it covers |
|---|---|---|
| MDN Geolocation API | https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API | getCurrentPosition, PositionOptions, errors, secure context, Permissions-Policy |
MDN watchPosition |
https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/watchPosition | Watcher signature, clearWatch |
| MDN Permissions API | https://developer.mozilla.org/en-US/docs/Web/API/Permissions_API | navigator.permissions.query, change event |
MDN <geolocation> element |
https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/geolocation | Experimental declarative permission control (Chrome 144+) |
| W3C Geolocation spec | https://www.w3.org/TR/geolocation/ | Normative model, privacy requirements |
@vercel/functions reference |
https://vercel.com/docs/functions/functions-api-reference/vercel-functions-package | geolocation(), ipAddress() |
| Vercel request headers | https://vercel.com/docs/headers/request-headers | x-vercel-ip-country, -country-region, -city, -latitude, -longitude, -timezone, -continent, -postal-code |
Cloudflare Request (request.cf) |
https://developers.cloudflare.com/workers/runtime-apis/request/ | IncomingRequestCfProperties geo fields |
| Google Geocoding API v4 | https://developers.google.com/maps/documentation/geocoding/geocoding-v4-overview | Forward / reverse / place geocoding, destinations |
| Google Places API (New) | https://developers.google.com/maps/documentation/places/web-service/nearby-search | Nearby / Text Search, Autocomplete, field masks |
| Google Maps Platform pricing | https://developers.google.com/maps/billing-and-pricing/pricing | Per-SKU free caps (since 2025-03-01) |
| Mapbox Geocoding v6 | https://docs.mapbox.com/api/search/geocoding/ | Forward / reverse, temporary vs permanent |
| Nominatim usage policy | https://operations.osmfoundation.org/policies/nominatim/ | Public OSM geocoder rules (1 req/s, forbidden uses) |
Versions & prices (verified 2026-10-20)
| Item | Value |
|---|---|
@vercel/functions |
3.10.1 |
@cloudflare/workers-types |
5.20261019.1 (or generate with wrangler types) |
next |
16.4.2 (middleware.ts is now proxy.ts) |
| Google Geocoding (Essentials) | 10,000 free / month, then $5.00 / 1,000 |
| Google Places Nearby Search Pro / Text Search Pro | 5,000 free / month, then $32.00 / 1,000 |
| Google Place Details Essentials / Pro | 10,000 / 5,000 free, then $5.00 / $17.00 per 1,000 |
| Google Autocomplete Requests | 10,000 free, then $2.83 / 1,000 (Session Usage: unlimited free) |
| Google Dynamic Maps / Static Maps | 10,000 free, then $7.00 / $2.00 per 1,000 |
| Mapbox Temporary Geocoding | 100,000 free / month, then $0.75 / 1,000 |
| Mapbox Permanent Geocoding | no free tier, $5.00 / 1,000 (1–500k) |
| Mapbox Map Loads (GL JS) | 50,000 free, then $5.00 / 1,000 |
| Nominatim (public OSM server) | free, max 1 req/s, strict usage policy |
The shape of a position
A success callback receives a GeolocationPosition: a coords object plus a timestamp (epoch ms).
coords field |
Meaning | Notes |
|---|---|---|
latitude / longitude |
WGS84 decimal degrees (numbers) | The PII. Treat as sensitive. |
accuracy |
Radius of confidence, metres | Always present. ~5–20 m with GPS, hundreds with Wi-Fi. |
altitude / altitudeAccuracy |
Metres | null on most phones. |
heading |
Degrees from true north | null when stationary. |
speed |
m/s | null unless moving. |
Error code |
Constant | Your move |
|---|---|---|
1 |
PERMISSION_DENIED |
Fall back to IP / manual entry. The browser won't re-prompt. |
2 |
POSITION_UNAVAILABLE |
Retry or fall back. |
3 |
TIMEOUT |
Retry with a longer timeout. |
interface PositionOptions {
enableHighAccuracy?: boolean; // default false — true asks for GPS (slower, more battery)
timeout?: number; // default Infinity (ms) — max wait for a fix
maximumAge?: number; // default 0 (ms) — accept a cached fix up to this old
}
Pattern 1 — check permission, then getCurrentPosition
Query the Permissions API first so you can tailor the UX; trigger the prompt from a user gesture after explaining why.
// lib/geolocation.ts — full version in examples/browser-geo.ts
export type GeoState = "granted" | "denied" | "prompt" | "unsupported";
export async function getGeoPermission(): Promise<GeoState> {
if (typeof navigator === "undefined" || !("geolocation" in navigator)) return "unsupported";
if (!("permissions" in navigator)) return "prompt";
try {
const status = await navigator.permissions.query({ name: "geolocation" });
return status.state; // "granted" | "denied" | "prompt"
} catch {
return "prompt";
}
}
export function getCurrentPosition(
options: PositionOptions = { enableHighAccuracy: true, timeout: 10_000, maximumAge: 60_000 },
): Promise<GeolocationPosition> {
return new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition(resolve, reject, options);
});
}
flowchart TD
A["Feature needs location"] --> B{"navigator.geolocation exists?"}
B -->|"no"| F["IP default / manual address entry"]
B -->|"yes"| C["permissions.query(geolocation)"]
C --> D{"state?"}
D -->|"granted"| G["getCurrentPosition · use fix"]
D -->|"prompt"| E["Show rationale · user gesture triggers prompt"]
D -->|"denied"| F
E --> H{"User choice"}
H -->|"allow"| G
H -->|"block"| F
Progressive enhancement: the <geolocation> element (experimental)
MDN now documents a declarative <geolocation> HTML element (HTMLGeolocationElement) that renders a browser-controlled "use location" button with a consistent permission UI. It is experimental, not Baseline — Chrome / Chrome Android 144+ only. Attributes include autolocate and watch; read element.position / element.error in its location event. Feature-detect with typeof HTMLGeolocationElement === "function" and keep the navigator.geolocation path as the fallback (put the fallback button inside the element). Don't build a product flow that depends on it yet.
iframes
The geolocation Permissions-Policy directive defaults to self. An embedded third-party map/widget needs <iframe src="…" allow="geolocation"> (and your Permissions-Policy header must not block it).
Pattern 2 — watchPosition with React cleanup
watchPosition fires on position change and returns an id you must pass to clearWatch.
"use client";
import { useEffect, useState } from "react";
type Fix = { lat: number; lng: number; accuracy: number; at: number };
export function useWatchPosition(active: boolean) {
const [fix, setFix] = useState<Fix | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!active || typeof navigator === "undefined" || !("geolocation" in navigator)) return;
const watchId = navigator.geolocation.watchPosition(
(pos) => {
const c = pos.coords;
setFix({ lat: c.latitude, lng: c.longitude, accuracy: c.accuracy, at: pos.timestamp });
setError(null);
},
(err) => setError(`(${err.code}) ${err.message}`),
{ enableHighAccuracy: true, timeout: 15_000, maximumAge: 5_000 },
);
return () => navigator.geolocation.clearWatch(watchId); // release the GPS radio
}, [active]);
return { fix, error };
}
Foreground only. Once the tab is backgrounded or closed, updates stop. For genuine background tracking you need a native app (or the WhatsApp "share live location" feature on Kenya-targeted projects); design ops flows around periodic foreground check-ins.
Accuracy & battery trade-offs
| Goal | enableHighAccuracy |
maximumAge |
Source | Cost |
|---|---|---|---|---|
| Rough default (store finder centre) | false |
large (5 min) | Wi-Fi/cell/cache | cheap |
| One-off pin on a map | true |
0 |
GPS | one GPS wake |
| Live route tracking | true |
small (5 s) | GPS continuous | battery-heavy |
Request high accuracy only when the UI plots a precise point; stop watchers the moment the screen isn't visible; gate continuous tracking behind an explicit "I'm on a delivery" state.
Geofencing (foreground)
No native web geofence. Keep a target point + radius and compute haversine distance on each watchPosition tick:
export function distanceMeters(a: [number, number], b: [number, number]): number {
const R = 6_371_000;
const toRad = (d: number) => (d * Math.PI) / 180;
const dLat = toRad(b[0] - a[0]);
const dLng = toRad(b[1] - a[1]);
const h =
Math.sin(dLat / 2) ** 2 +
Math.cos(toRad(a[0])) * Math.cos(toRad(b[0])) * Math.sin(dLng / 2) ** 2;
return 2 * R * Math.asin(Math.sqrt(h));
}
// inside watchPosition success: if (distanceMeters(here, dropoff) < 50) markArrived();
Server-side / background geofencing: push points to the backend and evaluate there (PostGIS ST_DWithin(geog, ST_MakePoint(lng, lat)::geography, meters)). Note PostGIS and GeoJSON order is lng, lat.
IP geolocation at the edge (coarse, consent-free)
Vercel — geolocation(request) from @vercel/functions
geolocation() just reads the x-vercel-ip-* headers Vercel's proxy injects, so it works in any Vercel Function runtime (Node.js default or Edge), in route handlers, and in the Next.js 16 proxy.ts. NextRequest.geo / NextRequest.ip were removed in Next.js 15.
// app/api/geo/route.ts — full version in examples/edge-geo.ts
import { geolocation } from "@vercel/functions";
export function GET(request: Request) {
const geo = geolocation(request);
return Response.json({
country: geo.country ?? "US", // ISO 3166-1 alpha-2
countryRegion: geo.countryRegion ?? null, // e.g. "FL" — the user's state
city: geo.city ? decodeURIComponent(geo.city) : null,
timezone: request.headers.get("x-vercel-ip-timezone"), // not in geolocation()
source: "ip",
precise: false,
});
}
Gotchas (verified against the package's Geo type, v3.10.1):
latitude/longitudeare strings —Number.parseFloatbefore maths. They're a city centroid, never "the user's location".geo.regionis the Vercel edge region ("iad1"), not the user's state — usecountryRegion.x-vercel-ip-cityis RFC 3986-encoded for non-ASCII names —decodeURIComponent.x-vercel-ip-timezoneandx-vercel-ip-continentexist as headers but aren't returned bygeolocation().- Everything is
undefinedundernext dev— always default.
Next.js 16: the middleware file convention is deprecated and renamed proxy (export function proxy(request), default runtime Node.js). See examples/proxy.ts.
Cloudflare Workers — request.cf
// full version in examples/cloudflare-geo.ts
export default {
async fetch(request: Request): Promise<Response> {
const cf = request.cf as IncomingRequestCfProperties | undefined;
const country = cf?.country ?? request.headers.get("CF-IPCountry") ?? "US";
return Response.json({ country, regionCode: cf?.regionCode ?? null, city: cf?.city ?? null });
},
} satisfies ExportedHandler;
request.cf geo fields: country, city, continent, region (name, e.g. "Texas"), regionCode ("TX"), postalCode, metroCode, latitude/longitude (strings), timezone, isEUCountry, plus colo (data centre) and asn. Not populated in the dashboard/Playground preview.
Accuracy ceiling: city, and often wrong. Mobile carrier NAT (very common in Kenya, common on US carriers too) and VPNs skew results by city or country. Use IP geo to default a locale/currency/store, never for access control, fraud decisions, or tax.
Geocoding & places (server-side only)
Coordinates mean nothing to a customer; addresses do. Geocoding is always a server-side call so the key never ships to the browser. (A Maps JavaScript API key in the browser is normal, but it must be a separate key restricted by HTTP referrer and to the Maps JS API only.)
Google Maps Platform
- Billing model (since 2025-03-01): the flat $200/month credit is gone; each SKU has its own monthly free usage cap — Essentials 10,000, Pro 5,000 (some "IDs only" SKUs unlimited). See the pricing table above.
- Geocoding API v4 is GA at
geocode.googleapis.com/v4/...(v3maps.googleapis.com/maps/api/geocode/jsonstill works and is not on the Legacy list). v4 renames fields to camelCase:results[].formattedAddress,location.latitude/longitude,granularity(waslocation_type),addressComponents[].longText;language→languageCode,region→regionCode(no default in v4 — v3 defaulted tous). Errors use HTTP status codes, notstatusstrings. PassX-Goog-Api-Keyand aX-Goog-FieldMask.- Forward:
GET https://geocode.googleapis.com/v4/geocode/address/{URL-encoded address} - Reverse:
GET https://geocode.googleapis.com/v4/geocode/location/{lat},{lng} granularityvalues:ROOFTOP,RANGE_INTERPOLATED,GEOMETRIC_CENTER,APPROXIMATE— treat the last two as low confidence and ask for a pin.- Google warns not to call v4 directly from client-side JavaScript (key abuse risk). Default quota 25 QPS.
- Forward:
- Places API (legacy) is Legacy as of 2025-03-01 and cannot be enabled in new Cloud projects. Use Places API (New):
POST https://places.googleapis.com/v1/places:searchNearby/places:searchText/places:autocomplete.X-Goog-FieldMaskis required and decides the billed SKU (asking forplaces.displayNamemakes it a Pro call). NearbymaxResultCount≤ 20. Directions/Distance Matrix are likewise Legacy → use the Routes API.
// Reverse geocode (v4) — full helpers incl. Places Nearby + Mapbox fallback in examples/geocode-server.ts
const res = await fetch(`https://geocode.googleapis.com/v4/geocode/location/${lat},${lng}`, {
headers: {
"X-Goog-Api-Key": process.env.GOOGLE_MAPS_API_KEY ?? "",
"X-Goog-FieldMask": "results.formattedAddress,results.location,results.granularity,results.placeId",
},
});
const { results = [] } = (await res.json()) as {
results?: Array<{ formattedAddress?: string; granularity?: string }>;
};
const address = results[0]?.formattedAddress ?? null;
Google's Maps Platform terms restrict caching/storing most returned content — read the service-specific terms before persisting addresses or coordinates that came from Google (persisting the coordinates the user gave you, e.g. a pin, is your own data).
Mapbox Geocoding v6
- Forward
GET https://api.mapbox.com/search/geocode/v6/forward?q=…&access_token=…; reverse…/v6/reverse?longitude=…&latitude=…&access_token=…. GeoJSON features, coordinates in [lng, lat] order. Rate limit 1,000 req/min. - Temporary results (default) may not be cached or stored; add
permanent=trueto store them — billed as Permanent Geocoding ($5.00/1,000, no free tier) vs Temporary (100k free, then $0.75/1,000). - v5 (
/geocoding/v5/mapbox.places) is documented as the "previous version"; build new code on v6.
Nominatim (OpenStreetMap)
The public server (nominatim.openstreetmap.org) is donated capacity with a strict policy: max 1 request/second per application, a real identifying User-Agent/Referer, visible OSM attribution (ODbL), cache results, and be able to switch providers without an app update. Forbidden: client-side autocomplete, systematic/grid reverse queries, and using it as the geocoder for package/vehicle-tracking apps or reselling results. That rules it out for delivery/dispatch products (e.g. boda dispatch) and for production autocomplete. Use it only for low-volume, user-triggered lookups in internal tools — or self-host Nominatim / use a commercial OSM-based provider.
Provider choice
| Need | Default pick |
|---|---|
| US address search / autocomplete in a product | Google Places API (New) Autocomplete + session tokens, or Mapbox Search Box |
| Reverse-geocode a pin for display | Google Geocoding v4 (10k free) → Mapbox Temporary (100k free) fallback |
| Store geocoded results permanently | Mapbox Permanent Geocoding, or Google with terms check |
| "Nearest X" over your own locations | PostGIS / haversine in your DB — no Places call at all |
| Internal/low-volume tooling | Nominatim (within policy) |
Kenya addressing & pin-drop (Kenya-targeted projects only)
Most Kenyan deliveries have no usable street address — people give landmarks ("opposite Naivas, blue gate"). So for Kenya-targeted products:
- Pin-primary. On WhatsApp flows, ask the customer to share a location pin (WhatsApp location message) — that's GPS-quality and needs no browser permission. Free text is the fallback, geocoded with
regionCode=KE(v4) /components=country:KE(v3) and region bias. - Confidence gate. A geocode with
granularityGEOMETRIC_CENTER/APPROXIMATE(v3location_typeorpartial_match) is low-confidence: never auto-dispatch a pickup from it — nudge for a pin; let a low-confidence drop-off proceed but flagneeds_review. Clamp absurd distances (e.g. > 50 km in a city) as geocode errors. (This is the boda-dispatch spec's policy; if that code moves to Geocoding v4, maplocation_type→granularity.) - Reverse-geocode pins so riders/operators see a human label, and keep the customer's landmark text alongside it.
- Plus Codes (
plusCode.globalCodein Google responses) are a shareable fallback "address" where no street address exists. - Never use the public Nominatim server for dispatch — its policy bans vehicle/package-tracking use.
- 2G/3G and budget Android: lazy-load any map SDK, prefer a Static Maps image or no map at all on WhatsApp-first flows, and keep live tracking short.
Privacy & compliance
Engineering guidance, not legal advice — confirm with counsel before launching location features.
United States (default)
| Law | What it says about location | Engineering consequence |
|---|---|---|
| California CCPA/CPRA (Civ. Code §1798.140) | "Precise geolocation" = device data locating a consumer within a circle of 1,850 ft radius; it is sensitive personal information | Disclose it at collection; honour the "Limit the Use of My Sensitive Personal Information" right — use it only for the service the user asked for |
| Virginia CDPA (§59.1-575, -578) | "Precise geolocation data" = within 1,750 ft; sensitive data → opt-in consent to process; controllers must not sell or offer for sale precise geolocation data | Explicit consent before collecting; no selling/sharing for consideration, ever |
| Oregon OCPA (HB 2008) | Sale of precise geolocation (1,750 ft, past or present) banned since 2026-01-01, for all consumers | Same: never sell; check every analytics/ads SDK that might receive it |
| Other state comprehensive privacy laws (Colorado, Connecticut, Texas, Maryland, …) | Commonly list precise geolocation as sensitive data needing consent; Maryland's MODPA is stricter still (not re-verified in the 2026-10-20 refresh — check each statute) | Design to the strictest: consent, minimisation, no sale |
| FTC Act §5 | The FTC has pursued unfair-practice cases over selling/sharing sensitive location data (not re-verified this refresh) | Don't pass raw location to ad/data-broker SDKs |
Design rules that satisfy all of the above:
- Consent before collection, with a plain-language rationale shown before the browser prompt; record the consent (timestamp, purpose, version).
- Minimise precision. Round to the coarsest value the feature needs before storing — 2 decimals ≈ 1.1 km (below the "precise" threshold), 3 ≈ 110 m, 4 ≈ 11 m. Store the result (nearest store id) rather than the raw trail when you can.
- Purpose limitation & no sale/sharing. Never forward lat/lng to analytics, ad pixels, or LLM prompts unless that's the stated purpose. Strip it from Sentry events/breadcrumbs and logs.
- Retention. Short TTL for location history (e.g. delete delivery trails 30–90 days after completion); support access/deletion requests.
- Security. Encrypt at rest, Supabase RLS / Neon role scoping so users read only their own rows, no location in URLs or client bundles.
- Revocation is real. Listen for the Permissions
changeevent; stop tracking and persistence immediately ondenied. Once denied, the browser won't re-prompt — never nag. - IP addresses and IP-derived geo are personal data too under most privacy regimes. Don't log them alongside user ids.
Kenya-targeted projects — KDPA 2019
Location is personal data under Kenya's Data Protection Act, 2019. Same playbook: lawful basis (usually consent — freely given, specific, informed, revocable), purpose limitation, minimisation, defined retention, data-subject rights (access, correction, erasure), and registration with the ODPC where required. See COMPLIANCE_GUIDE.md.
Environment variables
Secrets (store via the secrets vault / Vercel env, never NEXT_PUBLIC_*):
GOOGLE_MAPS_API_KEY=AIza...server-restricted
MAPBOX_ACCESS_TOKEN=pk.eyJ...server-side-token
Non-secret settings:
| Setting | Example | Notes |
|---|---|---|
NEXT_PUBLIC_GOOGLE_MAPS_BROWSER_KEY |
AIza… |
Separate key, HTTP-referrer-restricted to your domains and to Maps JavaScript API only. Public by design. |
NEXT_PUBLIC_MAPBOX_PUBLIC_TOKEN |
pk.eyJ… |
Mapbox public (pk.) token with URL restrictions, for GL JS map tiles only. |
GEO_DEFAULT_COUNTRY |
US (or KE on Kenya-targeted projects) |
Fallback when IP geo is missing. |
NOMINATIM_USER_AGENT |
codeamani-internal-tool/1.0 (ops@…) |
Required identifying UA if you use the public Nominatim server. |
Never put the server-side key/token (GOOGLE_MAPS_API_KEY, MAPBOX_ACCESS_TOKEN) in client code.
codeAmani notes
- US-first default. Edge IP geo (
geolocation(request)) seeds country/state/currency/nearest-store on first render withcountry ?? "US"; the precise browser fix is opt-in, triggered from a button, for features that truly need it. - Store finder / "near me". One-shot
getCurrentPositionon tap → server query over our own locations (PostGISST_DWithinor haversine) → no Places API call needed. Only call Places (New) when searching Google's POI data, with the tightest field mask. - Precise location is sensitive data. Consent record + rationale before the prompt, round before storing, short retention, never sold/shared, never in logs, analytics, Sentry, or LLM prompts (Claude/OpenAI routing included — send the derived result, e.g. "Nairobi CBD", not coordinates, unless the feature requires it).
- Keys server-side.
GOOGLE_MAPS_API_KEY/MAPBOX_ACCESS_TOKENlive in the vault / Vercel env and are used only from route handlers or server actions (import "server-only"). The browser gets a separate referrer-restricted key. - Budget the free caps. Google Geocoding 10k/month and Places Pro 5k/month go fast — cache what the terms allow, debounce autocomplete with session tokens, set daily quotas in Cloud Console, and put Sentry alerts on 429/403 responses.
- Payments are unrelated to location. Don't gate Stripe (default rail) on IP country; for Kenya-targeted projects, M-Pesa availability is decided by the project, not by geo-IP.
- Kenya-targeted projects: pin-primary capture via WhatsApp location messages, Google geocode fallback with
regionCode=KEand a confidence gate, Plus Codes as the address fallback, KDPA consent, render times in Africa/Nairobi (EAT, UTC+3) while storing UTC, and design for 2G/3G + budget Android (no always-on high-accuracy watchers). - HTTPS everywhere.
navigator.geolocationneeds a secure context — fine on Vercel/Cloudflare andlocalhost; never on a plain-HTTP preview or LAN IP.
Official docs:
- https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API
- https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/watchPosition
- https://developer.mozilla.org/en-US/docs/Web/API/Permissions_API
- https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/geolocation
- https://www.w3.org/TR/geolocation/
- https://vercel.com/docs/functions/functions-api-reference/vercel-functions-package
- https://vercel.com/docs/headers/request-headers
- https://developers.cloudflare.com/workers/runtime-apis/request/
- https://developers.google.com/maps/documentation/geocoding/geocoding-v4-overview
- https://developers.google.com/maps/documentation/places/web-service/nearby-search
- https://developers.google.com/maps/billing-and-pricing/pricing
- https://docs.mapbox.com/api/search/geocoding/
- https://operations.osmfoundation.org/policies/nominatim/