From f1ec8f36882e91a7cd4eef675f190619ec78a1c3 Mon Sep 17 00:00:00 2001 From: Sandeep Saini Date: Thu, 23 Feb 2023 17:51:26 -0500 Subject: [PATCH] added support for geoLocation --- .../script.js | 47 +++++++++++++++++-- 1 file changed, 43 insertions(+), 4 deletions(-) diff --git a/All Projects/10. Weather App Using Vanilla JavaScript/script.js b/All Projects/10. Weather App Using Vanilla JavaScript/script.js index 674a904..33b6633 100644 --- a/All Projects/10. Weather App Using Vanilla JavaScript/script.js +++ b/All Projects/10. Weather App Using Vanilla JavaScript/script.js @@ -23,12 +23,51 @@ const forecastCondition = document.querySelectorAll( ".forecast-weather-condition" ); + +const getCurrentLocation = () => { + return new Promise((resolve, reject) => { + if (navigator.geolocation) { + navigator.geolocation.getCurrentPosition( + (position) => { + resolve({ + latitude: position.coords.latitude, + longitude: position.coords.longitude, + }); + }, + () => { + reject('Unable to retrieve location data'); + } + ); + } else { + reject('Geolocation is not supported by this browser'); + } + }); +}; + + + + const onPageLoad = async () => { - const defaultApiCall = await fetch( - `https://api.weatherapi.com/v1/forecast.json?key=e9f03c0935864a1ba58105924231102&q=kolkata&days=7` - ); - const defaultWeatherData = await defaultApiCall.json(); + let locationData; + try { + locationData = await getCurrentLocation(); + } catch (error) { + console.error(error); + locationData = { latitude: null, longitude: null }; + } + +const apiCallWithLocation = `https://api.weatherapi.com/v1/forecast.json?key=e9f03c0935864a1ba58105924231102&q=${locationData.latitude},${locationData.longitude}&days=7`; + +const defaultApiCall = `https://api.weatherapi.com/v1/forecast.json?key=e9f03c0935864a1ba58105924231102&q=kolkata&days=7`; + +const data = await fetch( + locationData.latitude && locationData.longitude + ? apiCallWithLocation + : defaultApiCall +); + + const defaultWeatherData = await data.json(); currTemp.innerText = defaultWeatherData.current.temp_c; // weatherImage.src = defaultWeatherData.current.condition.icon;