Plot R Data With googleVis

[This article was first published on W. Andrew Barr's Paleoecology Blog, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Here is a little code snippet that shows how to do two things

  1. Use the Google Maps API to resolve place names into lat-long coordinate pairs.
  2. Plot R dataframes that contain lat-long data (for example from #1) onto Google Maps for quick visualization using the googleVis package.  The embedded map looks a little wonky here but it looks perfectly normal when you plot it locally in your browser. (Note: you need an internet connection for these maps to plot properly). 

//-->

-->

Data: plotData • Chart ID: MapID71b85742e7
R version 2.14.1 (2011-12-22) • googleVis-0.2.15Google Terms of UseData Policy
require(XML)
require(googleVis)
 
 
####functions borrwed from http://statisfaction.wordpress.com/2011/10/05/calling-google-maps-api-from-r/
 
getDocNodeVal=function(doc, path)
{
   sapply(getNodeSet(doc, path), function(el) xmlValue(el))
}
 
gGeoCode=function(str)
{
  library(XML)
  u=paste('http://maps.google.com/maps/api/geocode/xml?sensor=false&address=',str)
  doc = xmlTreeParse(u, useInternal=TRUE)
  str=gsub(' ','%20',str)
  lat=getDocNodeVal(doc, "/GeocodeResponse/result/geometry/location/lat")
  lng=getDocNodeVal(doc, "/GeocodeResponse/result/geometry/location/lng")
  list(lat = lat, lng = lng)
}
 
#### End functions borrowed from http://statisfaction.wordpress.com/2011/10/05/calling-google-maps-api-from-r/
 
# get some names of paleoanthropological sites in France. 
placeNames<-c("Cro Magnon","La Ferrassie","Chauvet Cave","La Chapelle aux Saints", "Le Moustier")
 
#resolve the placenames into latlong
latLong<-lapply(placeNames, FUN=gGeoCode)
 
#format the latlong coordinates into the proper format lat:long
latLongFormatted<-lapply(latLong,FUN=function(x){
 paste(x$lat[1],x$lng[1],sep=":")
})
 
#create a dataframe, formatting the place name string first and making the latlong a vector, not list
plotData<-data.frame(name=placeNames,latlong=unlist(latLongFormatted))
 
sites<-gvisMap(plotData,locationvar="latlong",tipvar="name", options=list(mapType='normal'))
plot(sites)

To leave a comment for the author, please follow the link and comment on their blog: W. Andrew Barr's Paleoecology Blog.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)