Question

I'm creating a simple application to get the user's coordinates, plug them into the Forecast API, and get back the current weather. Things seem to be working smoothly for the first 2 parts but when it's all put together, the coordinates are not passed properly into the API call even though they are printed just fine. Pretty confused and appreciate any help.

<!DOCTYPE html>
<html>
    <body>
    <p>Here's the weather:<p>
    <p id="weather"><p>

    <p>Here's the coordinates:<p>
    <p id="coordinates"><p>

    <button onclick="b()">Submit</button>
        <script>

        function b(){

            var apiKey = 'b04dbf475994a98f5849aa6856a4596d';
            var url = 'https://api.forecast.io/forecast/';

            var data;
            var lati = 0;
            var longi = 0;

          navigator.geolocation.getCurrentPosition(getCoordinates);

          function getCoordinates(position) {
            lati = position.coords.latitude;
            longi = position.coords.longitude;
          }

            $.getJSON(url + apiKey + "/" + lati + "," + longi + "?callback=?", function(data) {
              console.log(data);
              $('#weather').html(data.currently.temperature);
              $('#coordinates').html(lati + "," + longi);


            });
        }
        </script>

        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

    </body>
</html>
Was it helpful?

Solution

Try adding the $.get into your function that collects the geolocation. I suspect that is asynchronous.

function getCoordinates(position) {
    lati = position.coords.latitude;
    longi = position.coords.longitude;

    $.getJSON(url + apiKey + "/" + lati + "," + longi + "?callback=?", function(data) {
        console.log(data);
        $('#weather').html(data.currently.temperature);
        $('#coordinates').html(lati + "," + longi);
    }); 
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top