利用prototype和GOOGLE的weather api做天气预报
想拿prototype练练手,就用prototype做个天气预报吧。
Google Weather API 只支持美国地区使用邮政编码进行查询,例如:
http://www.google.com/ig/api?hl=zh-cn&weather=94043
(94043 为 山景城, 美国加州 的邮政编码)
而除了美国以外的地区需要使用经纬度坐标作为参数才能执行 Google Weather API, 例如:
http://www.google.com/ig/api?hl=zh-cn&weather=,,,30670000,104019996
(30670000,104019996 为 成都, 中国大陆 的经纬度坐标)
要其它地区的经纬度坐标,可以通过 Google API 提供的国家代码列表及相应的城市经纬度坐标列表可以查询到,以下是 Google API 提供的查询参数:
http://www.google.com/ig/countries?output=xml&hl=zh-cn
ASP演示:http://www.knowsky.com/tools/tianqiyubao.asp
(查询 Google 所支持的所有国家的代码,并以 zh-cn 简体中文显示)
http://www.google.com/ig/cities?output=xml&hl=zh-cn&country=cn
:<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title> New Document </title>
<meta name="Generator" content="EditPlus">
</head>
<script language="javascript" src="prototype.js"></script>
<script language="javascript">
//取得中国所有的城市
function getCity()
{
var url = "http://www.google.com/ig/cities";
var cityPara = {method:"get" ,
parameters:"output=xml&hl=zh-cn&country=cn" ,
onComplete:showCityRespose
};
var cityRequest = new Ajax.Request( url , cityPara);
}
function showCityRespose(originalRequest)
{
cityInfo = originalRequest.responseXML;
cityNodes = cityInfo.getElementsByTagName("city");
for(var i=0;i<cityNodes.length;i++){
var city = cityNodes[i];
var cityName = getData( city , "name");
var latitude = getData( city ,"latitude_e6");
var longitude= getData( city ,"longitude_e6");
var option =document.createElement("option");
$("city").options.add(option);
option.innerText = cityName;
option.value=",,,"+latitude+","+longitude;
}
}
function forecast(city)
{
$("result").innerHTML = "请稍等";
var url = "http://www.google.com/ig/api";
var para = {method:"get" ,
parameters:"hl=zh-cn&weather="+city ,
onComplete:showResult
};
var forecastRequest = new Ajax.Request(url , para);
}
//显示预报结果
function showResult(originalRequest)
{
$("result").innerHTML = "";
resultXML = originalRequest.responseXML;
forecastNodes = resultXML.getElementsByTagName("forecast_conditions");
for(i=0;i<forecastNodes.length;i++){
var oneNode = forecastNodes[i];
var weekday = getData( oneNode , "day_of_week");
var low = getData( oneNode , "low");
var high = getData( oneNode , "high");
var icon = getData( oneNode , "icon");
var result = document.createElement("div");
result.appendChild(document.createTextNode(weekday));
result.appendChild(document.createElement("br"));
result.appendChild(document.createTextNode("最低温度"+low));
result.appendChild(document.createElement("br"));
result.appendChild(document.createTextNode("最高温度"+high));
result.appendChild(document.createElement("br"));
var image = document.createElement("img");
image.setAttribute("src" , "http://www.google.com"+icon);
result.appendChild(image);
$("result").appendChild(result);
}
}