๐Ÿ“ JavaScript

Geolocation API โ€” Location-Aware Features Done Right

๐Ÿ“… Jul 4, 2026 โฑ 2 min read

"Find nearby X" features start here โ€” with the same permission discipline as notifications.

The API

navigator.geolocation.getCurrentPosition(
  (pos) => {
    const { latitude, longitude, accuracy } = pos.coords;
    showNearby(latitude, longitude);
  },
  (err) => {
    // 1 = denied, 2 = unavailable, 3 = timeout
    showManualCityPicker();          // ALWAYS have a fallback
  },
  { enableHighAccuracy: false, timeout: 8000, maximumAge: 300000 }
);

Distance between two points (Haversine)

function distanceKm(lat1, lon1, lat2, lon2) {
  const R = 6371, toRad = (d) => (d * Math.PI) / 180;
  const dLat = toRad(lat2 - lat1), dLon = toRad(lon2 - lon1);
  const a = Math.sin(dLat/2)**2 +
            Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) * Math.sin(dLon/2)**2;
  return 2 * R * Math.asin(Math.sqrt(a));
}

Project idea: "colleges near me" or a campus-navigation helper โ€” geolocation + a static coordinates list + this formula. Free APIs for more: see 5 free APIs.

โ† All Articles