0Pricing
React Academy · Lesson

Geolocation API in React Components

Request and track the user's location with the Geolocation API, handle permissions, and clean up watchers.

Geolocation API in React Components is a free React Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the React Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

One-Time Position Read

navigator.geolocation.getCurrentPosition(successCallback, errorCallback, options) requests the device location once. The success callback receives a GeolocationPosition object. This is appropriate when you need the location once, such as finding the nearest store on button click, rather than tracking ongoing movement.

Continuous Position Tracking

navigator.geolocation.watchPosition(successCallback, errorCallback, options) continuously fires the callback whenever the device position changes. It returns a numeric watchId. This is suitable for real-time use cases like delivery tracking or turn-by-turn navigation where the position must stay current.

The Position Object

The GeolocationPosition object contains a coords property with latitude, longitude, and accuracy (in meters). Additional optional fields include altitude, altitudeAccuracy, heading, and speed. The timestamp field records when the position was captured.

Geolocation Error Codes

The error callback receives a GeolocationPositionError with a numeric code property. Code 1 is PERMISSION_DENIED (user refused), code 2 is POSITION_UNAVAILABLE (hardware or network failure), and code 3 is TIMEOUT (the request took too long). Always handle all three cases.

Clearing the Watch on Cleanup

A watchPosition listener runs indefinitely until you stop it. In useEffect, return a cleanup function that calls navigator.geolocation.clearWatch(watchId). If you forget the cleanup, the watcher continues running after the component unmounts, draining the battery and potentially updating unmounted state.

Building useGeolocation Hook

A useGeolocation hook manages a status state with four possible values: idle (not yet requested), loading (request in progress), success (position received), and error (failed). It also holds the position and errorMessage in state. Components receive a clean, consistent interface.

Handling Permission Denial Gracefully

When the user denies geolocation, show a helpful message explaining why the feature needs location access and how to re-enable it in browser settings. Never show a raw error code to users. Offer a manual address entry fallback so the feature remains usable without location permission.

HTTPS Requirement for Geolocation

Like most powerful browser APIs, geolocation is restricted to secure contexts. navigator.geolocation is undefined on plain HTTP pages. During development on localhost, it works without HTTPS. In production, always ensure your app is served over HTTPS or users will never be prompted for permission.

Accuracy and Timing Options

The optional third argument to getCurrentPosition and watchPosition accepts an options object. enableHighAccuracy: true requests GPS-level precision at the cost of more power. timeout sets the maximum milliseconds to wait. maximumAge allows a cached position if it was captured within the specified milliseconds.

Real-World Use Cases

Geolocation enables features like "find a store near me", delivery driver tracking on a map, weather based on current city, location-tagged posts, and distance calculations between the user and a destination. Always communicate clearly to users why the app needs their location before requesting permission.

Testing Geolocation in Development

Chrome DevTools allows you to set a fake device location. Open DevTools, go to the three-dot menu, select More tools, then Sensors. You can type in latitude and longitude coordinates to simulate any location. This is far faster than physically traveling to test location-dependent features.

Geolocation Error Codes

What does a GeolocationPositionError code of 1 mean?

Lesson Recap: Geolocation API in React

Use getCurrentPosition for a one-time read and watchPosition for continuous tracking. Always call clearWatch in the useEffect cleanup. Build a useGeolocation hook with idle, loading, success, and error states. Handle permission denial gracefully and remember that geolocation requires HTTPS in production.

Frequently asked questions

Is the “Geolocation API in React Components” lesson free?

Yes — the full text of “Geolocation API in React Components” is free to read here on the web, and the React Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the React Academy course, upgrade to CoddyKit PRO.

What will I learn in “Geolocation API in React Components”?

Request and track the user's location with the Geolocation API, handle permissions, and clean up watchers. You practise React Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start React Academy?

No prior experience is required. React Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Geolocation API in React Components” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this React Academy lesson?

Yes. Every React Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Clipboard API: Copy and Paste in React
  2. Geolocation API in React Components
  3. Notifications API and Permission Handling
  4. IntersectionObserver for Scroll-Triggered Effects
← Back to React Academy