2017-10-04 91 views
0

我在Code Pen上編寫了一個Web應用程序,它可以獲取用戶位置並顯示當前的本地天氣。我成功地拉取了經度和緯度,但我似乎無法從API調用中獲取所需的JSON信息。從Open Weather API中提取信息

我用AJAX解析它,我相信我已經完成了Official API Documentation的要求,但它不起作用,數據甚至不會顯示在控制檯上。我已經看過很多答案,但我無法得到它的工作。

我想補充的信息裏面BLOCKQUOTE

if (navigator.geolocation) { 
 
    //Return the user's longitude and latitude on page load using HTML5 geolocation API 
 
    window.onload = function() { 
 
    function getCurrentLocation (position) { 
 
     
 
     latitude = position.coords.latitude; 
 
     longitude = position.coords.longitude; 
 
     
 
     console.log(latitude); 
 
     console.log(longitude); 
 

 
     $.getJSON("http://api.openweathermap.org/data/2.5/weather?lat=" + latitude + "&lon=" + longitude + "&APPID=b7aaa3a349294d5706002e82df3de1ea&units=metric", function (data) { 
 
     console.log(data); 
 
     console.log(weather.main.temp); 
 
     $(".city").append(name + " "); 
 
     $(".temperature").append(temp + " "); 
 
     $(".weatherdescription").append(field + " "); 
 
      }) 
 
      
 
     }; 
 
    } 
 
    
 
     navigator.geolocation.getCurrentPosition(getCurrentLocation); 
 
    }; 
 
<h1 class="jumbotron" style="color:white"><em>The Weather Today</em></h1> 
 

 
<div class="container-fluid"> 
 
    <div class = "row text-center"> 
 
    </div> 
 
    <div id="weather" class = "row text-center"> 
 
    <div class = "col-xs-12 well message"> 
 
     <blockquote id = "raw_json"> 
 
     <div class="weatherbox"> 
 

 
     <strong class="city">{CITY NAME HERE}</strong> 
 
    <br/> 
 
     <span class="temperature">{X} °C</span> 
 
    <br/> 
 
     <span class="weatherdescription">{WEATHER DESCRIPTION HERE}</span> 
 
     <br/> 
 

 
    </div> 
 
    </blockquote> 
 
    </div> 
 
    </div> 
 
    <div class = "row text-center"> 
 
    <div class = "col-xs-12"> 
 
     
 
    </div> 
 
    </div> 
 
</div>

回答

0

與以下替換您的JavaScript代碼,它應該工作。

if (navigator.geolocation) { 
    //Return the user's longitude and latitude on page load using HTML5 geolocation API 
    window.onload = function() { 
     navigator.geolocation.getCurrentPosition(getCurrentLocation); 

    } 

} 


function getCurrentLocation(position) { 

    latitude = position.coords.latitude; 
    longitude = position.coords.longitude; 

    console.log(latitude); 
    console.log(longitude); 

    $.getJSON("http://api.openweathermap.org/data/2.5/weather?lat=" + latitude + "&lon=" + longitude + "&APPID=b7aaa3a349294d5706002e82df3de1ea&units=metric", function (data) { 
     console.log(data); 
     console.log(weather.main.temp); 
     $(".city").append(name + " "); 
     $(".temperature").append(temp + " "); 
     $(".weatherdescription").append(field + " "); 
    }) 

}; 

CODEPEN:https://codepen.io/azimjs/pen/KXybpa?editors=0011

+0

這似乎解決座標問題,謝謝!但API調用仍然爲空... – user736493

+0

有語法錯誤。我已經更新了codepen。如果解決了您的問題,請將其標記爲已接受的答案。謝謝! –

+0

這樣做了,謝謝!你能詳細說明我所做的語法錯誤嗎? – user736493