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' ) ;
6
6
// 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' ) ;
10
10
11
11
const fetchData = async ( url ) => {
12
12
try {
@@ -26,17 +26,35 @@ const updateWeatherInfo = (result) => {
26
26
dateTime . innerText = `${ result . location . localtime } ` ;
27
27
temp . innerText = `${ result . current . temp_c } °C` ;
28
28
} ;
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
+ ) ;
33
32
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 ( ) => {
35
51
try {
36
52
const { value } = input ;
37
53
const result = await getData ( value ) ;
38
54
updateWeatherInfo ( result ) ;
39
55
} catch ( error ) {
40
- cityName . innerText = " Error to fetch weather" ;
56
+ cityName . innerText = ' Error to fetch weather' ;
41
57
}
42
58
} ) ;
59
+
60
+ locat . addEventListener ( 'click' , ( ) => navigator . geolocation . getCurrentPosition ( gotlocation , failedlocation ) ) ;
0 commit comments