Search code examples
javascriptjqueryajaxapigetjson

jQuery.getJSON() not working on page load. Works fine inside a click event


I'm making a "show-you-local-wather-app"(freecodecamp), and I want it to get the data on page load. But nothing happens. I quite new at this so I'm wondering if I've missed something obvious.

It works just fine if I put it inside $("#some_button").on("click", etc...

I've tried putting it inside $(document).ready without any succes. What am I missing here?

var latitude, longitude;
var apiKey = "9b6a0d53a4ed3ff657c6ff6e18ffa42f";
var url;

function success(pos) {
    var crd = pos.coords;
    latitude = crd.latitude;
    longitude = crd.longitude;
    url = "http://api.openweathermap.org/data/2.5/weather?lat=" + latitude + "&lon=" + longitude + "&units=metric&appid=" + apiKey;
};

navigator.geolocation.getCurrentPosition(success);

// AJAX call

$.getJSON(url, function(data) {
    $("#location").html(data.name + ", " + data.sys.country);
    $("#weather_type").html(data.weather[0].description);
    var imgURL = data.weather[0].icon + ".png";
    $("#icon").html("<img src='http://openweathermap.org/img/w/" + imgURL + "'>");
    $("#deg").html(data.main.temp);
    $("#windspeed").html(data.wind.speed);
    console.log(data);
});

I've made it with codepen if anyone want to see it. I'm using the OpenWeatherMap API.

Thanks!


Solution

  • Here is better solution, If your navigator.geolocation.getCurrentPosition(success) successfully returns then run runner() function.

    Here is quite simple examples Cordova Doc

    $(document).ready(function() { 
    var latitude, longitude;
    var apiKey = "9b6a0d53a4ed3ff657c6ff6e18ffa42f";
    var url;
    
    function success(pos) {
        var crd = pos.coords;
        latitude = crd.latitude;
        longitude = crd.longitude;
        url = "http://api.openweathermap.org/data/2.5/weather?lat=" + latitude + "&lon=" + longitude + "&units=metric&appid=" + apiKey;
    
        runner(url);
    };
    
    navigator.geolocation.getCurrentPosition(success);
    
    // AJAX call
     function runner(url){
      $.getJSON(url, function(data) {
    
        $("#location").html(data.name + ", " + data.sys.country);
        $("#weather_type").html(data.weather[0].description);
        var imgURL = data.weather[0].icon + ".png";
        $("#icon").html("<img src='http://openweathermap.org/img/w/" + imgURL + "'>");
        $("#deg").html(data.main.temp);
        $("#windspeed").html(data.wind.speed);
        console.log(data);
      });
    }; //end of runner
    
    }); //end of document.ready