0

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>
4

1 回答 1

0

尝试将其添加$.get到收集地理位置的函数中。我怀疑这是异步的。

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);
    }); 
}
于 2013-08-08T22:39:13.657 回答