从开放天气API中提取信息

时间:2017-10-04 18:59:00

标签: javascript jquery json openweathermap codepen

我正在Code Pen上编写一个Web应用程序,它会获取用户位置并显示当前的当地天气。我成功地提取了纬度和经度,但我似乎无法从API调用中获取所需的JSON信息。

我正在使用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>

1 个答案:

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