1

I've found this free weather API that gives you a forecast when you send an HTTP GET request - the forecast is delivered in JSON. A request could look like this:

Examples of JSON format:
Seaching by city name: api.openweathermap.org/data/2.5/weather?q=London,uk
Seaching by geographic coordinats: api.openweathermap.org/data/2.5/weather?lat=35&lon=139 Seaching by city ID: api.openweathermap.org/data/2.5/weather?id=2172797

So the response you get back is obviously defined by the end of the url, where some variables are located.

I've seen that you can use the jQuery function getJSON() to create an object out of the text file you get with an HTTP GET request, and you can also use variables with it to change the url. For an example doing this:

var person = "john";
$.getJSON("https://graph.facebook.com/" + person, function(person){

    $.each(person, function(key, value){
        document.write(key+": "+value+"<br />"); 
    });
}); 

Gives the output

id: 779695190
first_name: John
gender: male
last_name: Chan
locale: en_US
name: John Chan
username: John


However, when I try to use this with the weather API it doesn't work - there is no output. (Doing it without url-variables here for simplicity.) The below code is how I thought it would be done (but apparantly not).

$.getJSON("api.openweathermap.org/data/2.5/weather?q=London,uk", function(forecast){
    var temperature = forecast.main.temp;
    document.write(temperature);
});

See the JSON structure for the forecast here: http://bugs.openweathermap.org/projects/api/wiki/Weather_Data

So basically my questions are: How would I append the url-variables to the weather-api-urls (and making sure the request can be both city name or coordinates)? And how would I access the retrieved data once I got it from the server?

4

2 回答 2

1

首先,您可以读取 lat & long 值或邮政编码或城市 ID,然后可以通过调用包含 ajax 的函数来附加它们以调用给定参数的 api wrt。见下文,我只使用 lat long 进行了尝试来自浏览器的值。获得结果后,您可以像访问任何其他 json 对象一样访问它们。

function success(position) {
    var lat = position.coords.latitude;
    var long = position.coords.longitude;
    var timstp = position.timestamp;
    var myDate = new Date(timstp).toLocaleString();
    //console.log("Lat="+lat+"Long="+long+"timstp="+timstp+"date="+myDate); 

    $.ajax({
      url: "http://api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + long + "&appid=690660b930904f0cee1975853d5a2375",
      dataType: 'jsonp',
      success: function(results) {
        console.log(results);

   
      }
    });
}

于 2016-03-28T13:34:44.527 回答
0

可能我没有正确理解您的答案,但是如果您想在 url 中为 openweathermap api 附加一个变量,则代码是:

<script type="text/javascript">
$(document).ready(function(){
var variable='London'
$.getJSON("http://api.openweathermap.org/data/2.5/weather?q="+variable+",uk&callback", function(data){  
    console.log(data)
    console.log(data.main.temp_min)
    console.log(data.main.temp_max)
});

})
</script>
于 2014-05-04T15:49:34.490 回答