How to create a KML file using R

r kml
Vijay Barve picture Vijay Barve · Oct 18, 2011 · Viewed 16.7k times · Source

I have written a R script to get some map point data (Latitude and Longitude values). I am able to plot them in R and visualize them. But now I want to generate a KML file from this data and view using Google Earth. So that I can share it with colleagues and they can see it on Google Earth too.

What is the best method / package to do this ?

Answer

rcs picture rcs · Oct 18, 2011

Check the writeOGR function in the rgdal package. Here is a simple example:

library("sp")
library("rgdal")
data(meuse)
coordinates(meuse) <- c("x", "y")
proj4string(meuse) <- CRS("+init=epsg:28992")
meuse_ll <- spTransform(meuse, CRS("+proj=longlat +datum=WGS84"))
writeOGR(meuse_ll["zinc"], "meuse.kml", layer="zinc", driver="KML") 

The objects exported are SpatialPointsDataFrame, SpatialLinesDataFrame, or SpatialPolygonsDataFrame objects as defined in the sp package.

R> class(meuse)
[1] "SpatialPointsDataFrame"
attr(,"package")
[1] "sp"

For writing with the KML driver, note that the geometries should be in geographical coordinates with datum WGS84.