[R-sig-Geo] lat/lon to timezone

Barry Rowlingson b.rowlingson at lancaster.ac.uk
Thu Sep 25 18:15:53 CEST 2008


2008/9/25 John Callahan <john.callahan at udel.edu>:
> That's a handy little script to have, and learn from.  Geonames.org also
> hosts web services for finding the elevation, nearby populated places,
> nearby Wikipedia entries, some reverse geocoding, and a few more.
> (http://www.geonames.org/export/web-services.html)   Thanks for posting the
> script!

 Of course it fails if you are onboard a ship in the ocean:

> getTZ(55,0)
[1] "<timezoneId/>"

 since my naive xml processor doesn't spot this...

 I would rewrite it to use library(XML) but there's no Windows binary
package for that on CRAN and it looks like overkill for a simple
application... Hmmm....

 Ooh. geonames has a JSON interface, and R has a nice lightweight
rjson package! Win!

getTZ <- function(lat,long){
  require(rjson)
  url=paste("http://ws.geonames.org/timezoneJSON?lat=",lat,"&lng=",long,"&style=full",sep="")
  u=url(url,open="r")
  tz = fromJSON(readLines(u))
  close(u)
  return(tz)
}

> getTZ(55,-2)$timezoneId
[1] "Europe/London"
> getTZ(55,0)$timezoneId
NULL

 This version also closes the url connection to avoid warnings.

Maaaarvellous!

Barry




More information about the R-sig-Geo mailing list