The Geolocation Engineer builds features that are aware of where users are and where things are relative to each other. Geolocation is deceptively complex: coordinates are spherical (not flat), distance calculations must account for the Earth's curvature, and the browser Geolocation API requires user permission that 30% of users will deny. Always have a fallback.
Proximity Search with PostGIS
-- Install PostGIS extension
CREATE EXTENSION IF NOT EXISTS postgis;
-- Store location as geography (spherical, uses metres) not geometry (flat)
ALTER TABLE locations ADD COLUMN coords geography(POINT, 4326);
-- Update from lat/lng:
UPDATE locations SET coords = ST_MakePoint(lng, lat)::geography
WHERE lng IS NOT NULL AND lat IS NOT NULL;
-- Create spatial index (required for fast queries)
CREATE INDEX locations_coords_idx ON locations USING GIST(coords);
-- Find locations within 5km of a point (fastest with geography)
SELECT id, name, ST_Distance(coords, ST_MakePoint(-0.1276, 51.5074)::geography) AS distance_metres
FROM locations
WHERE ST_DWithin(
coords,
ST_MakePoint(-0.1276, 51.5074)::geography,
5000 -- metres
)
ORDER BY distance_metres
LIMIT 20;
-- Geofencing: check if a point is inside a polygon
SELECT ST_Contains(
ST_GeomFromText('POLYGON((...))', 4326)::geography,
ST_MakePoint(-0.1276, 51.5074)::geography
);
Mapbox GL JS Integration
import mapboxgl from 'mapbox-gl';
import 'mapbox-gl/dist/mapbox-gl.css';
import { useEffect, useRef } from 'react';
export function Map({ locations }: { locations: { lat: number; lng: number; name: string }[] }) {
const mapRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!mapRef.current) return;
mapboxgl.accessToken = process.env.NEXT_PUBLIC_MAPBOX_TOKEN!;
const map = new mapboxgl.Map({
container: mapRef.current,
style: 'mapbox://styles/mapbox/light-v11',
center: [-0.1276, 51.5074],
zoom: 12,
});
// Add markers
locations.forEach(({ lat, lng, name }) => {
new mapboxgl.Marker()
.setLngLat([lng, lat])
.setPopup(new mapboxgl.Popup().setHTML(`<strong>${name}</strong>`))
.addTo(map);
});
return () => map.remove();
}, [locations]);
return <div ref={mapRef} style={{ width: '100%', height: '400px' }} />;
}
Browser Geolocation with Fallback
async function getUserLocation(): Promise<{ lat: number; lng: number; source: string }> {
// Try browser Geolocation API first (accurate, requires permission)
if ('geolocation' in navigator) {
try {
const pos = await new Promise<GeolocationPosition>((resolve, reject) =>
navigator.geolocation.getCurrentPosition(resolve, reject, {
timeout: 5000,
maximumAge: 5 * 60 * 1000, // Accept 5-minute-old cached position
})
);
return { lat: pos.coords.latitude, lng: pos.coords.longitude, source: 'gps' };
} catch (_) {
// User denied or timed out - fall back to IP
}
}
// Fallback: IP geolocation (city-level accuracy, ~50km radius)
const res = await fetch('https://ipapi.co/json/');
const data = await res.json();
return { lat: data.latitude, lng: data.longitude, source: 'ip' };
}