如何通过 $.getjson 方法 JSON 准确获取天气 API

How to accurately access weather API via the $.getjson method JSON

我正在 FCC 上构建一个天气应用程序,但由于我的代码无法正常工作而卡住了。我没有收到要求浏览器访问我的位置的弹出请求。 我将该弹出请求包装在我的 button.click 函数中。 我是新手,我感到非常沮丧。我需要帮助!!

这是我的代码:

      var Api= "https://fcc-weather-api.glitch.me/api/current?";

        $(document).ready(function(){

        $("button").click(function(){

        if (navigator.geolocation) {

        navigator.geolocation.getCurrentPosition(function(position) {
            
         var lat = "lat=" + position.coords.latitude ;
            
         var lon = "lon=" + position.coords.longitude;

   $.get(Api+lat+"&"+ lon, function(result){

        $("#city").text(result.main.name);

        $("#country").text(result.sys.country);

        $("#weather").text(result.weather[0].main);

        $("#w-icon").text(result.weather[0].icon);

        $("#temp").text(result.main.temp);

        $("humidity").text(result.main.humidity);

        });


        });


        });
            else {

        console.log ("Geolocation is not supported by this browser");
    }
         });

https://codepen.io/Ojomiba/pen/dVgQeQ

在浏览器中打开开发者工具。

查看控制台。

阅读错误消息


Uncaught ReferenceError: lat is not defined

您在传递给 getCurrentPosition 的函数内部定义了 lat,但您正试图在该函数 外部 使用它。

您需要移动尝试使用它的代码,使其位于函数内部。