Write KML File in R

1k Views Asked by At

I am creating a shiny application where I allow the user to write the data out to either csv or kml. However, my code below does not write the features out to the kml file, such that when I open the KML in google earth it shows black dots and when clicked it displays the row index of the original data rather than All column values for that specific point. I was using writeOGR function but it was not writing the file, so I switched to using plotKML package. I want the user to choose where the file is saved (using the filename I specify with date and timestamp) and display in Google Earth all features of any given datapoint.

output$downloadData <- downloadHandler(
filename = function() {
  paste0("data_",Sys.Date(), input$download_type)
},
content = function(file) {
  if (input$download_type == ".csv"){
    write.csv(data, file, row.names = FALSE)
  } else if (input$download_type == ".KML") {

    features <- c("COLUMN_1", "COLUMN_2", "COLUMN_3") #These are the features I want displayed in Google Earth
    data[features] <- as.character(data[features])

    coordinates(data) <- ~X + Y
    proj4string(data) <- CRS("+proj=longlat +datum=WGS84")
    
    kml_description(data, caption = "Data",
                    delim.sign = "_", asText = F)
    kml(data, file = file) #Not sure why this produces points but doesn't display features in Google Earth

    #writeOGR(data, dsn = file, layer="Data", driver = "KML")
  }
})

enter image description here

1

There are 1 best solutions below

0
giocomai On

Getting a KML in a way that can be adeuqately read by Google Maps is not yet as easy as it should be.

You may want to give a try to export via the sf package and libkml.

sf::st_write(obj = an_sf_object, dsn = kml_file_path, driver = "libkml")

(you may need to install libkml on your server)

See also this function from the latlon2map package for a working (albeit less than ideal) implementation.