
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")


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)


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]


capitalize =
function(x)
{
  sprintf("%s%s", toupper(substring(x, 1, 1)), substring(x, 2))
}


tmp$countyName = gsub("^california,", "", m$names[tmp$countyNum + 1])


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)
    })


saveXML(doc, "polys.kml")

