Exporting KML from R

Google Earth has become a popular way of disseminating spatial data. KML is the data format required to do this. It is possible to load almost any type of spatial data format into R and export it as a KML file. In my experience R seems much quicker at doing this than many well-known GIS platforms, such as ArcGIS. The worksheet below explains how.

Data and Package Requirements:

London Cycle Hire Locations. Download.

Install the following packages (if you haven’t already done so):

maptools, rgdal (Mac users may wish to see here first).

Click here to view the tutorial code.


  1. Greg Cicconetti

    James, thanks for this. I was able to replicate with a dataset I have. To take your example to the next step, could we assign different colors to the pushpins based on the values of variables, e.g., different colors for each village or heat.colors for your capacity values?

    1. James Foreman

      Those pushpins are .png images so unfortunately you can’t just tell Google Earth to show them in a different colour.

      However, you could assign a different style to each point; (possibly by capacity, or the village) and then if you have different coloured .png images assigned to each style, Google Earth will display it correctly. (Creating all the different .png programmatically might be a little bit difficult, but I assume somebody has already solved that.)

      You’ll need to put the kml file this produces in the same directory as all the .png files, and then zip it and rename to .kmz before Google Earth will play nicely with it though.

  2. Wade

    Thank you for the information. If I export a KML (polygon), how can I “fill in” the area with a color, as opposed to viewing only the border?

    Example code
    setwd(“G:\GIS_SJR\GIS Shapefiles\Boundaries”)

    polygon <- readOGR(".", "20km_buffer_albers")

    polygonWGS <- spTransform(polygon, CRS("+proj=longlat +ellps=WGS84 +datum=WGS84"))

    writeOGR(polygonWGS, dsn="polygonWGS.kml", layer="polygonWGS", driver="KML")

  3. Mike

    The link to London_cycle_hire_locs.csv is invalid again.

    “Oops! Google Chrome could not connect to dl.dropbox.com”

    Perhaps you could manually specify a single example row of data in the tutorial code?

Comments are closed.