CodingNic

Loading, Errors & Geolocation

Connect the Use My Location Button

Loading, Errors & Geolocation 25 min read

Connect the Use My Location Button

Connect the Use My Location Button

Task

Use the browser’s Geolocation API and pass its coordinates into fetchByCoordinates().

Open

Add this click listener after the form listener.

Implementation

javascript
$("locationButton").addEventListener("click", () => {
  if (!navigator.geolocation) {
    return showError("Geolocation is not supported by this browser.");
  }

  showError("");
  showLoader(true);

  navigator.geolocation.getCurrentPosition(
    position => fetchByCoordinates(
      position.coords.latitude,
      position.coords.longitude
    ),
    () => {
      showLoader(false);
      showError("Location permission was denied or unavailable.");
    },
    { enableHighAccuracy: true, timeout: 10000 }
  );
});

getCurrentPosition() has a success callback and an error callback. The success callback receives coordinates; the error callback handles permission denial or unavailable location. The timeout prevents the request from waiting indefinitely.

Test

Click Use My Location and allow permission. Confirm the city/weather changes to your location. Test again with permission denied and verify the prepared error message appears.

Expected result

Geolocation now uses the same data and rendering pipeline as city search.

Checkpoint

Before moving on, confirm the expected result in the running app and make sure the browser console has no blocking errors.