Skip to content

Update currentLocation.js #12

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
272 changes: 125 additions & 147 deletions src/currentLocation.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,33 +41,29 @@ const defaults = {
size: 112,
animate: true,
};
class Weather extends React.Component {
state = {
lat: undefined,
lon: undefined,
errorMessage: undefined,
temperatureC: undefined,
temperatureF: undefined,
city: undefined,
country: undefined,
humidity: undefined,
description: undefined,
icon: "CLEAR_DAY",
sunrise: undefined,
sunset: undefined,
errorMsg: undefined,
};

componentDidMount() {
export default function Weather() {
const [lat, setLat] = useState(undefined);
const [lon, setLon] = useState(undefined);
// const [errorMessage, setErrorMessage] = useState(undefined);
const [temperatureC, setTemperatureC] = useState(undefined);
const [temperatureF, setTemperatureF] = useState(undefined);
const [city, setCity] = useState(undefined);
const [country, setCountry] = useState(undefined);
const [humidity, setHumidity] = useState(undefined);
const [description, setDescription] = useState(undefined);
const [icon, setIcon] = useState("CLEAR_DAY");
// const [sunrise, setSunrise] = useState(undefined);
// const [sunset, setSunset] = useState(undefined);

useEffect(() => {
if (navigator.geolocation) {
this.getPosition()
//If user allow location service then will fetch data & send it to get-weather function.
getPosition()
.then((position) => {
this.getWeather(position.coords.latitude, position.coords.longitude);
getWeather(position.coords.latitude, position.coords.longitude);
})
.catch((err) => {
//If user denied location service then standard location weather will le shown on basis of latitude & latitude.
this.getWeather(28.67, 77.22);
getWeather(28.67, 77.22); // Default location
alert(
"You have disabled location service. Allow 'This APP' to access your location. Your current location will be used for calculating Real time weather."
);
Expand All @@ -76,136 +72,118 @@ class Weather extends React.Component {
alert("Geolocation not available");
}

this.timerID = setInterval(
() => this.getWeather(this.state.lat, this.state.lon),
600000
);
}

componentWillUnmount() {
clearInterval(this.timerID);
}

// tick = () => {
// this.getPosition()
// .then((position) => {
// this.getWeather(position.coords.latitude, position.coords.longitude)
// })
// .catch((err) => {
// this.setState({ errorMessage: err.message });
// });
// }

getPosition = (options) => {
return new Promise(function (resolve, reject) {
const timerID = setInterval(() => getWeather(lat, lon), 600000);

return () => clearInterval(timerID);

// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

const getPosition = (options) =>
new Promise(function (resolve, reject) {
navigator.geolocation.getCurrentPosition(resolve, reject, options);
});
};
getWeather = async (lat, lon) => {
const api_call = await fetch(
`${apiKeys.base}weather?lat=${lat}&lon=${lon}&units=metric&APPID=${apiKeys.key}`
);
const data = await api_call.json();
this.setState({
lat: lat,
lon: lon,
city: data.name,
temperatureC: Math.round(data.main.temp),
temperatureF: Math.round(data.main.temp * 1.8 + 32),
humidity: data.main.humidity,
main: data.weather[0].main,
country: data.sys.country,
// sunrise: this.getTimeFromUnixTimeStamp(data.sys.sunrise),

// sunset: this.getTimeFromUnixTimeStamp(data.sys.sunset),
});
switch (this.state.main) {
case "Haze":
this.setState({ icon: "CLEAR_DAY" });
break;
case "Clouds":
this.setState({ icon: "CLOUDY" });
break;
case "Rain":
this.setState({ icon: "RAIN" });
break;
case "Snow":
this.setState({ icon: "SNOW" });
break;
case "Dust":
this.setState({ icon: "WIND" });
break;
case "Drizzle":
this.setState({ icon: "SLEET" });
break;
case "Fog":
this.setState({ icon: "FOG" });
break;
case "Smoke":
this.setState({ icon: "FOG" });
break;
case "Tornado":
this.setState({ icon: "WIND" });
break;
default:
this.setState({ icon: "CLEAR_DAY" });

const getWeather = async (lat, lon) => {
try {
const api_call = await fetch(
`${apiKeys.base}weather?lat=${lat}&lon=${lon}&units=metric&APPID=${apiKeys.key}`
);
const data = await api_call.json();
setLat(lat);
setLon(lon);
setCity(data.name);
setTemperatureC(Math.round(data.main.temp));
setTemperatureF(Math.round(data.main.temp * 1.8 + 32));
setHumidity(data.main.humidity);
setDescription(data.weather[0].main);
setCountry(data.sys.country);

switch (data.weather[0].main) {
case "Haze":
setIcon("CLEAR_DAY");
break;
case "Clouds":
setIcon("CLOUDY");
break;
case "Rain":
setIcon("RAIN");
break;
case "Snow":
setIcon("SNOW");
break;
case "Dust":
setIcon("WIND");
break;
case "Drizzle":
setIcon("SLEET");
break;
case "Fog":
case "Smoke":
setIcon("FOG");
break;
case "Tornado":
setIcon("WIND");
break;
default:
setIcon("CLEAR_DAY");
}
} catch (error) {
console.error(error.message); // Handle error
}
};

render() {
if (this.state.temperatureC) {
return (
<React.Fragment>
<div className="city">
<div className="title">
<h2>{this.state.city}</h2>
<h3>{this.state.country}</h3>
</div>
<div className="mb-icon">
{" "}
<ReactAnimatedWeather
icon={this.state.icon}
color={defaults.color}
size={defaults.size}
animate={defaults.animate}
/>
<p>{this.state.main}</p>
</div>
<div className="date-time">
<div className="dmy">
<div id="txt"></div>
<div className="current-time">
<Clock format="HH:mm:ss" interval={1000} ticking={true} />
</div>
<div className="current-date">{dateBuilder(new Date())}</div>
</div>
<div className="temperature">
<p>
{this.state.temperatureC}°<span>C</span>
</p>
{/* <span className="slash">/</span>
{this.state.temperatureF} &deg;F */}
</div>
return temperatureC ? (
<>
<div className="city">
<div className="title">
<h2>{city}</h2>
<h3>{country}</h3>
</div>

<div className="mb-icon">
<ReactAnimatedWeather
icon={icon}
color={defaults.color}
size={defaults.size}
animate={defaults.animate}
/>
<p>{description}</p>
</div>

<div className="date-time">
<div className="dmy">
<div id="txt"></div>

<div className="current-time">
<Clock format="HH:mm:ss" interval={1000} ticking={true} />
</div>

<div className="current-date">{dateBuilder(new Date())}</div>
</div>
<Forcast icon={this.state.icon} weather={this.state.main} />
</React.Fragment>
);
} else {
return (
<React.Fragment>
<img src={loader} style={{ width: "50%", WebkitUserDrag: "none" }} />
<h3 style={{ color: "white", fontSize: "22px", fontWeight: "600" }}>
Detecting your location
</h3>
<h3 style={{ color: "white", marginTop: "10px" }}>
Your current location wil be displayed on the App <br></br> & used
for calculating Real time weather.
</h3>
</React.Fragment>
);
}
}
}

export default Weather;
<div className="temperature">
<p>
{temperatureC}°<span>C</span>
</p>
<span className="slash">/</span>
{temperatureF} &deg;F
</div>
</div>
</div>

<Forcast icon={icon} weather={description} />
</>
) : (
<>
<img src={loader} style={{ width: "50%", WebkitUserDrag: "none" }} />
<h3 style={{ color: "white", fontSize: "22px", fontWeight: "600" }}>
Detecting your location
</h3>
<h3 style={{ color: "white", marginTop: "10px" }}>
Your current location wil be displayed on the App <br></br> & used for
calculating Real time weather.
</h3>
</>
);
}