While completing the Local Weather project, I came across $.getJSON
and $.ajax
, and read the former is just shorthand for the latter.
They both look very differnt and I’m having trouble seeing how I would write my code below using $.ajax() instead of .getJSON(). I’m hoping understanding how both work will help clear up some confusion I have about how to make API calls in general.
function showPoints(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
// AJAX request
var api = "https://api.openweathermap.org/data/2.5/weather?lat=" + latitude + "&lon=" + longitude + "&APPID=eec551a3788ea51493994e5edfb48781";
$.getJSON(api, function(data) {
var kTemp = data.main.temp;
var type = data.weather[0].description;
var city = data.name;
var country = data.sys.country;
var tempSwitch = true;
// temperature conversions
var fTemp = (kTemp * (9 / 5) - 459.67).toFixed(0);
var cTemp = (kTemp - 273).toFixed(0);
$("#temp").html(fTemp + "° " + "F");
$("#temp").click(function() {
if (tempSwitch === false) {
$("#temp").html(cTemp + "° " + "C");
tempSwitch = true;
} else {
$("#temp").html(fTemp + "° " + "F");
tempSwitch = false;
}
});
$("#weather").html(city + ", " + country);