Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get coordinates from a drawing object from an R leaflet map

Tags:

r

leaflet

I am building a shiny app where I would like to get the coordinates of a polygon from a leaflet map. Specifically, the shape is drawn using the Drawtoolbar from the leaflet.extras package. A simple example app is below.

My question is, how can I get the coordinates from the shape drawn on the map by the user? Thank you in advance.

library(shiny)
library(leaflet)
library(leaflet.extras)

# Define UI 
ui <- fluidPage(
  leafletOutput("mymap",height=800)
)

# Define server logic 
server <- function(input, output) {
  output$mymap <- renderLeaflet(
    leaflet() %>%
    addProviderTiles("Esri.OceanBasemap",group = "Ocean Basemap") %>%
    setView(lng = -166, lat = 58.0, zoom = 5) %>%
    addDrawToolbar(
      targetGroup='draw',
      editOptions = editToolbarOptions(selectedPathOptions = selectedPathOptions()))  %>%
  addLayersControl(overlayGroups = c('draw'), options =
                     layersControlOptions(collapsed=FALSE))
)

observeEvent(input$mymap_shape_click,{
   print(input$mymap_shape_click)
})

  observeEvent(input$mymap_click,{
    print(input$mymap_click)
  })
}

# Run the application
shinyApp(ui = ui, server = server)
like image 392
Steve Martell Avatar asked Feb 19 '18 01:02

Steve Martell


1 Answers

You need to observe the _draw_new_feature function

library(leaflet.extras)

# Define UI 
ui <- fluidPage(
  leafletOutput("mymap",height=800)
)

# Define server logic 
server <- function(input, output) {

  output$mymap <- renderLeaflet(
    leaflet() %>%
      addProviderTiles("Esri.OceanBasemap",group = "Ocean Basemap") %>%
      setView(lng = -166, lat = 58.0, zoom = 5) %>%
      addDrawToolbar(
        targetGroup='draw',
        editOptions = editToolbarOptions(selectedPathOptions = selectedPathOptions()))  %>%
      addLayersControl(overlayGroups = c('draw'), options =
                         layersControlOptions(collapsed=FALSE))
  )

  observeEvent(input$mymap_draw_new_feature,{
    feature <- input$mymap_draw_new_feature

    print(feature)

  })

}

# Run the application
shinyApp(ui = ui, server = server)
like image 78
SymbolixAU Avatar answered Oct 19 '22 20:10

SymbolixAU