Skip to content

added support for geoLocation #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 43 additions & 4 deletions All Projects/10. Weather App Using Vanilla JavaScript/script.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down