【问题标题】:Values Not Being Passed Using API & JS未使用 API 和 JS 传递值
【发布时间】:2013-08-10 20:03:40
【问题描述】:

我正在创建一个简单的应用程序来获取用户的坐标,将它们插入 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>

【问题讨论】:

    标签: javascript jquery api geolocation weather-api


    【解决方案1】:

    尝试将$.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);
        }); 
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-05
      • 1970-01-01
      • 1970-01-01
      • 2020-11-26
      • 1970-01-01
      • 2021-10-19
      • 1970-01-01
      • 2020-10-30
      相关资源
      最近更新 更多