Exporting and using KML Files

Google Earth is an extremely versatile tool for understanding geospatial data. Google Earth uses KML files to represent geospatial data. R will allow us to write our geospatial data to a KML file. To do this, you will have to install the maptools and the rgdal libraries. The code for writing a SpatialPointsDataFrame to a KML file is given below:

library(ggmap)
library(maptools)
library(rgdal)

data(crime)                                 #Load the Crime Data Set
crime<-crime[!is.na(crime$lat),]            #Get rid of the NA's in the crime data set
crime<-crime[1:100,]                        #Get only the first 100 records

coordinates(crime)<-c("lon","lat")          #Build a SpatialPointsData Frame
 proj4string(crime)<-CRS("+proj=longlat +datum=WGS84")

##The two lines below convert the month and day columns to character dat
##(both of these line are originally 'factor' data, which is not compatible)
crime$month<-as.character(crime$month)
crime$day<-as.character(crime$day)

##The one line of code below writes our SpatialPointsDataFrame to a KML File
writeOGR(crime, dsn="crime.kml", layer= "crime", driver="KML")

Now we just have to go to our working directory and double click on the KML file to open it in Google Earth (assuming that Google Earth is already installed on your computer)

alt text