3
votes

I'd like to export an sf object as a .kml file, with labels for each feature I'm interested in so I can view the data easily in Google Earth. I know you can click on the "info" button in Google Earth, but for hundreds of polygons, this isn't ideal.

For example, I'd like to label each polygon feature below using the column NAME. How can I modify the st_write call below to label the kml polygons so that they appear in the sidebar table of contents in Google Earth?

library(sf)
library(dplyr)

# sf includes this dataset
county_polygons <- st_read(system.file("shape/nc.shp", package="sf")) %>% 
st_transform(4326)


st_write(county_polygons , "test.kml", driver = "kml")

Here's a picture showing the lack of labels in Google Earth when this is imported as a kml file:

polygons with no labels

1
Hi, check this package: cran.r-project.org/web/packages/plotKML/plotKML.pdf . I used it before with success, placing labels and creating timelines. KML driver can't label polygons, you need to compute centroids and then place labels over points - aldo_tapia
Thanks @aldo_tapia, I've done that as a stop-gap for now, was hoping that with the improvements in sf, there would be a one-stop-shop kind of solution ... too much to ask? :P - Nova
I think sf is focused on spatial databases management, neither styles or labeling outside plot environment. A solution could be add a layer_options declaration from KML driver. I tried with NAME and NameField with no success - aldo_tapia

1 Answers

5
votes

Consider this code, using a different, although also well known & well loved dataset - the polygons of North Carolina counties from ns.shp shipped with {sf} package:

library(sf)
library(dplyr)


# dataset included with sf package
county_polygons <- st_read(system.file("shape/nc.shp", package="sf")) %>% 
  st_transform(4326) %>% # just because wgs84...
  select(Description = NAME) # see https://gdal.org/drivers/vector/kml.html#creation-options

st_write(county_polygons, "test.kml", driver = "kml", delete_dsn = TRUE)

It is built around the feature of KML export of DescriptionField (which is clickable in Google Earth) defaulting to sf column named Description.

enter image description here

If you want the feature's name in the sidebar instead, you can replace the word Description with Name in the code above.