Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 4d14cc3

Browse files
committed
add get location functionalities
1 parent fc136bb commit 4d14cc3

File tree

1 file changed

+32
-14
lines changed

1 file changed

+32
-14
lines changed

Source-Code/WeatherApp/script.js

Lines changed: 32 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
1-
const input = document.getElementById("input");
2-
const btn = document.getElementById("btn");
3-
const apiKey = "e3a46268fdc2475cb63214712240202";
4-
const cityName = document.getElementById("city-name");
5-
const dateTime = document.getElementById("date-time");
1+
const input = document.getElementById('input');
2+
const btn = document.getElementById('btn');
3+
const apiKey = 'e3a46268fdc2475cb63214712240202';
4+
const cityName = document.getElementById('city-name');
5+
const dateTime = document.getElementById('date-time');
66
// const icon = document.getElementById('icon');
7-
const temp = document.getElementById("temp");
8-
const country = document.getElementById("country");
9-
const locat = document.getElementById("getlocation");
7+
const temp = document.getElementById('temp');
8+
const country = document.getElementById('country');
9+
const locat = document.getElementById('getlocation');
1010

1111
const fetchData = async (url) => {
1212
try {
@@ -26,17 +26,35 @@ const updateWeatherInfo = (result) => {
2626
dateTime.innerText = `${result.location.localtime}`;
2727
temp.innerText = `${result.current.temp_c} °C`;
2828
};
29-
const getData = async (cityName) =>
30-
fetchData(
31-
`http://api.weatherapi.com/v1/current.json?key=${apiKey}&q=${cityName}&aqi=no`
32-
);
29+
const getData = async (cityName) => fetchData(
30+
`http://api.weatherapi.com/v1/current.json?key=${apiKey}&q=${cityName}&aqi=no`,
31+
);
3332

34-
btn.addEventListener("click", async () => {
33+
const getlocation = async (lat, long) => fetchData(
34+
`http://api.weatherapi.com/v1/current.json?key=${apiKey}&q=${lat},${long}&aqi=no`,
35+
);
36+
37+
const gotlocation = async (position) => {
38+
try {
39+
const result = await getlocation(
40+
position.coords.latitude,
41+
position.coords.longitude,
42+
);
43+
updateWeatherInfo(result);
44+
} catch (error) {
45+
cityName.innerText = 'Error fetching weather based on location';
46+
}
47+
};
48+
const failedlocation = () => console.log('failed to locate location');
49+
50+
btn.addEventListener('click', async () => {
3551
try {
3652
const { value } = input;
3753
const result = await getData(value);
3854
updateWeatherInfo(result);
3955
} catch (error) {
40-
cityName.innerText = "Error to fetch weather";
56+
cityName.innerText = 'Error to fetch weather';
4157
}
4258
});
59+
60+
locat.addEventListener('click', () => navigator.geolocation.getCurrentPosition(gotlocation, failedlocation));

0 commit comments

Comments
 (0)