Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Label kml features using `st_write`

Tags:

r

label

kml

r-sf

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

like image 943
Nova Avatar asked Oct 22 '25 14:10

Nova


1 Answers

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.

like image 57
Jindra Lacko Avatar answered Oct 25 '25 04:10

Jindra Lacko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!