Search code examples
pythonrshinyexportkml

Exporting .kml or .kmz from RShiny (with Python)


I had this problem for a few weeks. I couldn't figure out how to get RShiny to allow export of .kml or .kmz files, specifically ones created from a sourced Python package.

I finally figured it out day before yesterday. I don't know how to just make an answer, so I will add it as the accepted answer for anyone else who might come across this issue. There wasn't anything I could find that helped during my troubleshooting... so hopefully this helps the next person.


Solution

  • I searched pretty much everywhere I could think of to solve this problem, but nothing helped. I finally got it through trial and error of my code on both the R and Python sides. Here's what I found works (in RShiny):


    In ui, just make sure there is a downloadButton with the id of whatever you are trying to export with the downloadHandler. In this example, there would need to be two: one for 'download_kml' and another for 'download_kmz'.

    server <- function(input,output) {
    
    
    function_object <- reactive({python_class(args)})
    
    kml_show_object <- reactive({function_object()$show_kml})
    
    
    #------------------------------------------
    # TO EXPORT .KML
    
    output$download_kml <- downloadHandler(
    
        filename <- function() {
            'export.kml'
        },
        content <- function(file) {
            write(kml_show_object(), file)
        },
        contentType = 'application/vnd.google-earth.kml+xml'
        )
    
    #------------------------------------------
    # TO EXPORT .KMZ
    
    output$download_kmz <- downloadHandler(
        filename <- function() {
            'export.kmz'
        },
        content <- function(file) {
            write(kml_show_object(), file)
        },
        contentType = 'application/vnd.google-earth.kmz'
        )
    }
    
    shinyApp(ui = ui, server = server)
    

    This is using the simplekml package in Python to create a kml object. To get it to function right (on the R side), you can't just create the kml object. R doesn't know what to do with that. You have to assign a variable to kml.kml() inside the Python code. In this example, it is a class variable named 'show_kml', which gets assigned locally in R to the kml_show_object.


    If you need help with the Python code that makes the kml object, I can edit this to include it.

    Hope that helps!