Created
April 29, 2012 12:27
-
-
Save xccds/2550075 to your computer and use it in GitHub Desktop.
get weather data from wunderground
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
getweather <- function() { | |
library(RCurl) | |
library(RJSONIO) | |
library(XML) | |
# 输入需要查询的城市名称,若中国城市则输入拼音即可,如:beijin | |
city <- as.character(readline('please input the city name:')) | |
# 从google API处获得经纬度数据 | |
requestUrl<-paste("http://maps.googleapis.com/maps/api/geocode | |
/xml?address=",city,"&sensor=false", sep="") | |
xmlResult<-xmlTreeParse(requestUrl,isURL=TRUE) | |
root <- xmlRoot(xmlResult) | |
lat <-xmlValue(root[['result']][['geometry']][['location']][['lat']]) | |
lon <-xmlValue(root[['result']][['geometry']][['location']][['lng']]) | |
# 将经纬度数据输入到wunderground.com的API中获得天气数据 | |
# 注意你要申请自己的key放到your_key处 | |
url <- 'http://api.wunderground.com/api/your_key/conditions/ | |
forecast/lang:CN/q/' | |
finalurl <- paste(url,as.character(lat),',',as.character(lon), | |
'.json',sep='') | |
web <- getURL(finalurl) | |
raw <-fromJSON(web) | |
high <- raw$forecast$simpleforecast$forecastday[[2]]$high['celsius'] | |
low <- raw$forecast$simpleforecast$forecastday[[2]]$low['celsius'] | |
condition <- raw$forecast$simpleforecast$forecastday[[2]]$conditions | |
currenttemp <- raw$current_observation$temp_c | |
currentweather <- raw$current_observation$weather | |
result <-list(current=paste(currenttemp,'°C ',currentweather,sep=''), | |
tomorrow=paste(high,'°C','-',low,'°C ',condition,sep='')) | |
names(result) <-c('当前', '明天') | |
return(result) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
very helpful! THs!