I have this codepen Localweather App I have created two functions.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
$(document).ready(function() {
var city = "Newcastle";
city = getLocation();
//set city to location from function;
console.log ("city undefined?" +city);
//this is undefind, why?
getWeather(city).then(function(data) {
console.log(data);
var weatherType = data.weather[0].description;
var weatherId = data.weather[0].id;
var tempF = Math.round(data.main.temp);
var tempC = Math.round((tempF - 32) / 1.8);
var wind = data.wind.speed;
var name = data.name;
console.log(weatherType);
$('#weather').html(weatherType);
$('#temp').html(tempC + "°C");
$('#wind').html(tempF + "°F");
$('#icon').html(weatherId);
$('#location').html(name);
})
});
function getLocation() {
$.getJSON('http://ipinfo.io', function(data) {
console.log("data" + data);
city = data.city;
console.log("city" + city);
return city;
})
}
function getWeather(place) {
return $.getJSON('http://api.openweathermap.org/data/2.5/weather?q=' + place + '&units=imperial&APPID=90d625c068e3f3d7818b9e4237871e21');
}
</script>
A getWeather function that takes in a place and returns a weather object for that location. I also have a getLocation function that I want to return my city based on ip ( yes I know its not accurate but its what I want to use).
If I hardcode the city it works. But trying to use the city Variable from the getLoction function isnt working. I am guessing it is something to do with it been asynchronous but I though that by using a call back in the getLoction function it would return the 'city' which would 'then' be passed into the getWeather. Or have I got my thinking all wrong?
Aucun commentaire:
Enregistrer un commentaire