Skip to content

Instantly share code, notes, and snippets.

@VasVV
Last active November 8, 2023 16:18
Show Gist options
  • Save VasVV/38382915e0bbc65f4a581f1184381ccc to your computer and use it in GitHub Desktop.
Save VasVV/38382915e0bbc65f4a581f1184381ccc to your computer and use it in GitHub Desktop.
Weather App - JavaScript
var cityM;
const API = "AIzaSyAexH-F8hreUZqgZniExuKSmcD4D03kyvY";
class Storage {
constructor() {
this.city;
this.defaultCity = "Madrid";
}
getLocationData() {
if (!localStorage.getItem("city")) {
this.city = this.defaultCity;
} else {
this.city = localStorage.getItem("city");
}
return { city: this.city };
}
setLocationData(city) {
localStorage.setItem("city", city);
}
}
const storage = new Storage();
const weatherLocation = storage.getLocationData();
class UI {
constructor() {
this.location = document.getElementById("w-location");
this.desc = document.getElementById("w-desc");
this.string = document.getElementById("w-string");
this.details = document.getElementById("w-details");
this.icon = document.getElementById("w-icon");
}
filler(weather) {
this.location.textContent = cityM;
this.desc.textContent = weather[0]["WeatherText"];
this.string.textContent =
weather[0]["Temperature"]["Metric"]["Value"] + " C";
this.details.textContent =
weather[0]["Temperature"]["Imperial"]["Value"] + " F";
this.icon.setAttribute(
"src",
`https://developer.accuweather.com/sites/default/files/${
weather[0].WeatherIcon < 10
? "0" + weather[0].WeatherIcon
: weather[0].WeatherIcon
}-s.png`
);
}
}
class Weather {
constructor(city) {
this.apiKey = "RYj8Dbu79gye6Vv54TUGNhKos4rno3ss";
this.city = city;
this.cityCode = "";
}
async getLocation() {
navigator.geolocation.getCurrentPosition(function (position) {
let lat = position.coords.latitude;
let lon = position.coords.longitude;
const getInfo = fetch(
`https://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${lon}&key=${API}`
)
.then((data) => data.json())
.then((data) => {
let city = data.results[7].formatted_address.split(",")[0];
const responseData = fetch(
`https://dataservice.accuweather.com/locations/v1/cities/search?apikey=RYj8Dbu79gye6Vv54TUGNhKos4rno3ss&q=${city}&language=en-us&details=false`
)
.then((e) => e.json())
.then((e) => {
let cityCode;
cityCode = e[0]["Key"];
const weatherResponse = fetch(
`https://dataservice.accuweather.com/currentconditions/v1/${cityCode}?apikey=RYj8Dbu79gye6Vv54TUGNhKos4rno3ss&language=en-us&details=false`
)
.then((j) => j.json())
.then((j) => {
let location = document.getElementById("w-location");
let desc = document.getElementById("w-desc");
let string = document.getElementById("w-string");
let details = document.getElementById("w-details");
let icon = document.getElementById("w-icon");
location.textContent = city;
desc.textContent = j[0]["WeatherText"];
string.textContent =
j[0]["Temperature"]["Metric"]["Value"] + " C";
details.textContent =
j[0]["Temperature"]["Imperial"]["Value"] + " F";
icon.setAttribute(
"src",
`https://developer.accuweather.com/sites/default/files/${
j[0].WeatherIcon < 10
? "0" + j[0].WeatherIcon
: j[0].WeatherIcon
}-s.png`
);
});
});
})
.catch((err) => console.log(err));
});
console.log("cityM" + cityM);
}
async getWeather(city = this.city) {
const response = await fetch(
`https://dataservice.accuweather.com/locations/v1/cities/search?apikey=${this.apiKey}&q=${this.city}&language=en-us&details=false`
);
cityM = this.city;
const responseData = await response.json();
if (!responseData) {
let x = document.getElementById('error');
setTimeout(function() {
return x.setAttribute("display", "inline");
}, 3000);
}
this.cityCode = responseData[0]["Key"];
const weatherResponse = await fetch(
`https://dataservice.accuweather.com/currentconditions/v1/${this.cityCode}?apikey=${this.apiKey}&language=en-us&details=false`
);
const weatherResponseData = await weatherResponse.json();
return weatherResponseData;
}
changeCity(newCity) {
this.city = newCity;
}
}
const weather = new Weather(weatherLocation.city);
const ui = new UI();
const getLocation = () => {
weather.getLocation();
};
const getWeather = () => {
weather
.getWeather()
.then((res) => ui.filler(res))
.catch((err) => console.log(err));
};
document.addEventListener("DOMContentLoaded", getLocation);
document.addEventListener("DOMContentLoaded", getWeather);
document.getElementById("change-city").addEventListener("click", () => {
const city = document.getElementById("city").value;
weather.changeCity(city);
storage.setLocationData(city);
getWeather();
$("#locModal").modal("hide");
});
console.log("cityM" + cityM);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.1/popper.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.0/js/bootstrap.min.js"></script>
#error {
display: none
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootswatch/4.4.1/cerulean/bootstrap.min.css" rel="stylesheet" />
<div class='container'>
<div class='row'>
<div class='col-md-6 mx-auto text-center bg-primary mt-5 p-5 rounded'>
<h1 id='w-location'></h1>
<div id='error'><div class="alert alert-danger" role="alert">
This is a danger alert—check it out!
</div></div>
<h3 class='text-dark' id='w-desc'><h3>
<h3 id='w-string'></h3>
<img id='w-icon'>
<ul id='w-details' class='list-group mt-3'>
<li class='list-group-item' id='w-humidity'></li>
<li class='list-group-item' id='w-dewpoin'></li>
<li class='list-group-item' id='w-feels-like'></li>
<li class='list-group-item' id='w-wind'></li>
</ul>
<button type='button' class='btn btn-primary' data-toggle='modal' data-target='#locModal'>Change location</button>
</div>
</div>
</div>
<!-- modal -->
<div class="modal fade" id="locModal" tabindex="-1" role="dialog" aria-labelledby="locModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Choose location</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span area-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<form id='w-form'>
<div class='form-group'>
<label for='city'>City</label>
<input type='text' id='city'></input>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" id='change-city' class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment