I'm developing an air pollution app, but I'm unable to view either the city or the pollution index via geolocation.
How can I change the code to display both the city and the pollution index in my app?
I'm using the following API:
https://aqicn.org/json-api/doc/#api-Geolocalized_Feed-GetGeolocFeed
Here is the JS code:
const cityElement = document.querySelector(".city span");
const indexElement = document.querySelector(".indexAir span");
const air_key = '';
const air = {};
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
let latitude = position.coords.latitude;
let longitude = position.coords.longitude;
getData(latitude, longitude);
});
} else {
console.log("Geolocation in not supported by this browser");
}
}
function getData(latitude, longitude) {
let api = `https://api.waqi.info/feed/geo:${latitude};${longitude}/?token=${air_key}`;
fetch(api)
.then(function(response) {
let data = response.json();
return data;
})
.then(function(data) {
air.index = air.aqi;
air.city = air.city;
})
.then(function() {
showData();
})
}
// DISPLAY INFORMATIONS
function showData() {
cityElement.innerHTML = `${air.city}<span> </span>`;
indexElement.innerHTML = `${air.index}<span> </span>`;
}
//GET AIR POLLUTION FROM SEARCH BAR
btn_search.onclick = function() {
let city = document.getElementById('city').value;
let api = `https://api.waqi.info/search/?token=${air_key}&keyword=${city}`;
fetch(api)
.then(function(response){
let data = response.json();
return data;
})
.then(function(data){
air.city = data.data[0].station.name;
air.index = data.data[0].aqi;
air.time = data.data[0].time.stime;
})
.then(function(){
let elemCity = air.city;
let pollution = air.index;
showData();
changeBackground(pollution);
})
}
// CHANGE BACKGROUND INDEX AIR
function changeBackground(pollution){
if(pollution<=50){
index.style.background = "rgb(58, 194, 58)";
index.style.border = "rgb(58, 194, 58)";
}else if(pollution>=51 && pollution <=100) {
index.style.background = "rgb(242, 245, 54)";
index.style.border = "rgb(242, 245, 54)";
}else if(pollution>=101 && pollution <=150) {
index.style.background = "rgb(243, 156, 57)";
index.style.border = "rgb(243, 156, 57)";
}else if(pollution>=151 && pollution <=200) {
index.style.background = "rgb(245, 22, 22)";
index.style.border = "rgb(245, 22, 22)";
}else if(pollution>=201 && pollution <=300) {
index.style.background = " rgb(136, 69, 245)";
index.style.border = "rgb(136, 69, 245)";
}else if(pollution>300) {
index.style.background = "rgb(160, 59, 59)";
index.style.border = "rgb(160, 59, 59)";
}else {
index.style.background = "lightgrey";
index.style.border = "lightgrey";
}
}
If I wanted to search for a city after typing it using the enter key, what function should I type?
Another thing, would it be possible to create an error message when a city is not found?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…