From 0bb8b7ec5c22f8cc6f1c6ef943dbbacacdb28ba3 Mon Sep 17 00:00:00 2001 From: ItzCrazyKns <95534749+ItzCrazyKns@users.noreply.github.com> Date: Sat, 28 Jun 2025 13:49:17 +0530 Subject: [PATCH] feat(weather-widget): enable geolocation for weather data Replaces the previous commented-out geolocation logic with an implementation that uses the browser's geolocation API and reverse geocoding to determine the user's city. Falls back to approximate location if permission is denied or unavailable. --- src/components/WeatherWidget.tsx | 58 +++++++++++++++++++------------- 1 file changed, 34 insertions(+), 24 deletions(-) diff --git a/src/components/WeatherWidget.tsx b/src/components/WeatherWidget.tsx index e6a631e..d308bb4 100644 --- a/src/components/WeatherWidget.tsx +++ b/src/components/WeatherWidget.tsx @@ -31,30 +31,40 @@ const WeatherWidget = () => { city: string; }) => void, ) => { - /* - // Geolocation doesn't give city so we'll country using ipapi for now - if (navigator.geolocation) { - const result = await navigator.permissions.query({ - name: 'geolocation', - }) - - if (result.state === 'granted') { - navigator.geolocation.getCurrentPosition(position => { - callback({ - latitude: position.coords.latitude, - longitude: position.coords.longitude, - }) - }) - } else if (result.state === 'prompt') { - callback(await getApproxLocation()) - navigator.geolocation.getCurrentPosition(position => {}) - } else if (result.state === 'denied') { - callback(await getApproxLocation()) - } - } else { - callback(await getApproxLocation()) - } */ - callback(await getApproxLocation()); + if (navigator.geolocation) { + const result = await navigator.permissions.query({ + name: 'geolocation', + }); + + if (result.state === 'granted') { + navigator.geolocation.getCurrentPosition(async (position) => { + const res = await fetch( + `https://api-bdc.io/data/reverse-geocode-client?latitude=${position.coords.latitude}&longitude=${position.coords.longitude}&localityLanguage=en`, + { + method: 'GET', + headers: { + 'Content-Type': 'application/json', + }, + }, + ); + + const data = await res.json(); + + callback({ + latitude: position.coords.latitude, + longitude: position.coords.longitude, + city: data.locality, + }); + }); + } else if (result.state === 'prompt') { + callback(await getApproxLocation()); + navigator.geolocation.getCurrentPosition((position) => {}); + } else if (result.state === 'denied') { + callback(await getApproxLocation()); + } + } else { + callback(await getApproxLocation()); + } }; getLocation(async (location) => {