The purpose of this example is to illustrate how we can make an image map in Google Earth. Specifically, we will draw polygons for the boundaries of the counties in the Bay Area. When the viewer clicks anywhere within a county, we display a plot of the median house prices for each week. We reuse some of the plots created in the Image Maps examples. (See stat141 class notes.)
We will use the maps package to get the boundaries for the counties. We would be better off using more accurate boundaries.
library(maps)
load("~/Data/housing.Rda")
xlim = range(housing$long, na.rm = TRUE)
ylim = range(housing$lat, na.rm = TRUE)
m = map('county', xlim = xlim, ylim = ylim,
fill = TRUE, col = "transparent")
Now we create our KML document. We create the basic stub of a document and then add a Folder node to house our polygons.
library(RKML)
kdoc = createKMLDoc("County House Prices", "Sales price data for counties in the SF Bay Area",
list(longitude = mean(xlim), latitude = mean(ylim),
altitude = 250000))
doc = xmlRoot(kdoc)[["Document"]]
folder = newXMLNode("Folder", newXMLNode("name", "polygons"), parent = doc)
We split the polygon information so that we can get the polygon for each county.
i = cumsum(is.na(m$x)) w = !is.na(m$x) tmp = data.frame(x = m$x[w], y = m$y[w], countyNum = i[w]) i = i[w]
We change the names of the polygons and insert them into the data frame so we can identify the county corresponding to the boundary. We use this to display the corresponding plot.
tmp$countyName = gsub("^california,", "", m$names[tmp$countyNum + 1])
Next we create the Placemark nodes containing the polygons. We also add a <description> node to each displaying the name of the county and the plot.
by(tmp, i,
function(vals) {
node = kmlPolygon(vals[,1], vals[,2], parent = folder)
newXMLNode("description",
sprintf("<h1>%s<h1><img src='../Images/%s.png'/>", vals[1, "countyName"], vals[1, "countyName"]),
parent = node)
})
Finally, we can write the KML document to a file and then load it into Google Earth:
saveXML(doc, "polys.kml")