How to use the Geolocation API in web applications

· Category: JavaScript & Web

Short answer

The Geolocation API exposes the user's current position through navigator.geolocation.getCurrentPosition() and continuous tracking via watchPosition(), subject to user consent.

Details

A simple call looks like:

navigator.geolocation.getCurrentPosition(
  (pos) => console.log(pos.coords.latitude, pos.coords.longitude),
  (err) => console.error(err.code, err.message)
);

Always handle errors gracefully because users may deny permission or the device may lack a GPS signal. Error handling with try/catch is helpful for surrounding any custom logic you run after receiving coordinates. For real-time tracking, pair the API with async/await wrappers around watchPosition callbacks. Cache results responsibly and respect privacy by only requesting location when it genuinely improves the user experience.

Tips

  • Request high accuracy only when necessary; it drains battery faster.
  • Provide a fallback (e.g., ZIP code input) if permission is denied.
  • Stop watching position with clearWatch(id) when the component unmounts or the user leaves the page.