未使用API​​和API传递的值JS

时间:2013-08-08 22:35:45

标签: javascript jquery api geolocation weather-api

我正在创建一个简单的应用程序来获取用户的坐标,将它们插入到Forecast API中,然后恢复当前的天气。对于前两个部分,事情似乎顺利进行,但是当它们全部放在一起时,即使打印得很好,坐标也不能正确传递到API调用中。很困惑,感谢任何帮助。

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

1 个答案:

答案 0 :(得分: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);
    }); 
}