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:

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.


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

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

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

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:


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:

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

Official docs: