I'm working on a weather app, on top of having the option to get his geolocation the user can also input a city to get the weather info. I've been stuck for a while, I'm trying to get the info of the weather using the input of the user, using my api request(which is working on codepen // I'm working on VSCode). Im using the same url of my geoLocation but changing it to taking the city instead of the lon and lat as input, but I always get a ERROr 400, but I can't seem to locate the source of my error.
// Get weather from input
function getVal() {
var val = document.querySelector('#search-city').value;
const url = 'https://api.openweathermap.org/data/2.5/weather?q=' val '&appid={API key}&units=metric';
$.ajax({
url: url,
type: "GET",
dataType: 'json',
success: (data) => {
$('#city').text(data.name)
$('#condition').text(data.weather[0].main);
$('h1').text(Math.round(data.main.temp));
backgroundChange(data.weather[0].main);
},
error: () => {
return false
}
});
};
// Get weather using location
function geoLocation() {
if ('geolocation' in navigator) {
navigator.geolocation.getCurrentPosition((position) => {
let lat = position.coords.latitude;
let long = position.coords.longitude;
let url = 'https://api.openweathermap.org/data/2.5/weather?lat=' lat '&lon=' long '&appid={API Key}&units=metric';
$.ajax({
url: url,
type: "GET",
dataType: 'json',
success: (data) => {
$('#city').text(data.name)
$('#condition').text(data.weather[0].main);
$('h1').text(Math.round(data.main.temp));
backgroundChange(data.weather[0].main);
},
error: () => {
return false
}
});
})
};
});
I would really appreciate your help ! Thank you very much!!
// RESOLVED
At first I created the function outside of my onlick event and the API Call was made even before the event was called, so I think the input couldn't make it's way to the URL. Here is the modify version which is now working :
$('.search-icon').click( function getVal() {
var city = document.querySelector('#search-city').value;
const url = 'https://api.openweathermap.org/data/2.5/weather?q=' city '&appid=dc8c9152e8adaad0ec8bf635818c0d42&units=metric';
$.ajax({
url: url,
type: "GET",
dataType: 'json',
success: (data) => {
$('#city').text(data.name)
$('#condition').text(data.weather[0].main);
$('h1').text(Math.round(data.main.temp));
backgroundChange(data.weather[0].main);
},
error: () => {
return false
}
});
});
CodePudding user response:
I believe in this part of API's url "ppid={API Key}" you are passing as a string. You should inform your API key in order to fetch the data.
CodePudding user response:
Thanks for your responses but I found the solution ! Instead of creating an event using the function, I put the function in the event.