在网页中,有时候需要显示天气预报的信息,而网络中也有许多这方面的插件可以使用,但许多插件都有带有链接,且布局较为固定,不一定符合网页的要求。因此,需要根据一些API接口来自己实现天气预报功能。
在网络中,我们也可以查到许多关于天气预报的免费的API接口:
如:http://blog.youkuaiyun.com/fengyun1989/article/details/7341166
这篇博客里面介绍了谷歌、雅虎、中国天气网这三个API接口。本人通过测试,也证实了谷歌的天气预报API不能用了(http://bbs.youkuaiyun.com/topics/390316794?page=1),雅虎的API预报信息较少,且需要各个城市的代码,中国天气网的API是中央气象台的官方网站,天气预报信息较为详细,对于国内天气预报支持也较好,缺点是也需要城市ID,且国际城市数量较少。
当然,还有其他的天气预报的API可供使用:如腾讯、新浪等。
对于中国天气网,获得城市代码,有两种方法供使用:
1.获得当前IP地址,然后查询IP地址对应的城市名称,如果手里有较全的城市ID,就可以轻松的获得该城市的天气预报了。
根据IP地址查询对应城市名称的方法有很多,如新浪的API支持较好,而腾讯的API貌似不能用了。
新浪API的使用:http://mj.588cy.com/jquery/10.html
腾讯API的使用:http://wenwen.soso.com/z/q229100191.htm
http://www.cnblogs.com/xiaochaohuashengmi/archive/2010/07/06/1771892.html
2.根据中国天气网提供的API,访问网址:http://61.4.185.48:81/g/,就可得到你当前IP所在城市的代码,然后解析页面:http://m.weather.com.cn/data/所在城市ID.html,就可以得到当前城市详细的天气预报了。但缺点是,网址http://61.4.185.48:81/g/访问不稳定,有时候访问不了。
例子:
function getWeather() {
//request get current ip
$.ajax({url: 'http://61.4.185.48:81/g/', dataType: "script", success: function(result){
var weatherUrl; //Current city url
var provinceCode; //Current province code
var cityCode; //Current city code
if (id){
var url = "http://m.weather.com.cn/data/"+id+".html";
//according to current ip get current city detail info
json = getWeatherInfo(url);
}
var lishow = " <ul>";
lishow += "<li>"+json.city+" 今天 "+json.temp1+" "+json.weather1+"</li>";
lishow += "<li>"+json.city+" 明天 "+json.temp2+" "+json.weather2+"</li>";
lishow += "<li>"+json.city+" 后天 "+json.temp3+" "+json.weather3+"</li>";
lishow += "</ul>"
parseToday(lishow);
}, error: error, timeout: "3000"});
}
中国天气网API的使用:http://blog.mynook.info/2012/08/18/weather-com-cn-api.html
对于新浪的API使用,可以参考:http://mj.588cy.com/jquery/11.html
其他获得天气预报的方法:http://bbs.lampbrother.net/read-htm-tid-98992.html
如果想根据这些api接口得到天气预报信息,可以借鉴:http://blog.youkuaiyun.com/wei_ge163/article/details/8167478
以及http://julying.com/lab/weather/
最后贴出有人搜集整理的有关天气预报的api接口: