简体   繁体   English

未使用API​​和JS传递值

[英]Values Not Being Passed Using API & JS

I'm creating a simple application to get the user's coordinates, plug them into the Forecast API, and get back the current weather. 我正在创建一个简单的应用程序,以获取用户的坐标,将其插入Forecast API,并获取当前天气。 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. 前两个部分似乎工作正常,但是将它们放在一起后,即使打印得很好,坐标也无法正确传递到API调用中。 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>

Try adding the $.get into your function that collects the geolocation. 尝试将$.get添加到收集地理位置的函数中。 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);
    }); 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM