Creating and reading KML data

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.

Getting ready

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)

How to do it...

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

How it works...

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.

See Also

In the next recipe, we will learn how to work with ESRI shapefiles.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.233.34