In this recipe, we will learn how to read and write geographic data in Google's Keyhole Markup Language (KML) format, which can be used to visualize geographic data with Google Earth and Google Maps.
We will use the rgdal
package in this recipe. So, let's make sure it's installed and load it:
install.packages("rgdal") library(rgdal)
We will use data from the cities shapefile that's installed as part of the rgdal
package. First, we will write a KML file and then read it:
cities <- readOGR(system.file("vectors", package = "rgdal")[1],"cities") writeOGR(cities, "cities.kml", "cities", driver="KML") df <- readOGR("cities.kml", "cities")
In the preceding example, we first used the readOGR()
function to read the cities
shapefile dataset. The first argument is the folder (directory) where the data shapefile is and the second argument is the name of the shapefile (without the .shp
extension). We stored the object returned by the readOGR()
function as cities
, which is of the SpatialPointsDataFrame
class.
To create a KML file, we used the writeOGR()
function. We passed the cities
object as the first argument. The second argument specifies the name of the output KML file, the third argument specifies the shapefile layer name (without extension), and the fourth argument is the driver (in this case, KML
).
To read the KML file back into R, we used the readOGR()
function with only two arguments. The first argument specifies the KML data file to be read and the second argument specifies the name of the layer.
13.58.201.75