googleway icon indicating copy to clipboard operation
googleway copied to clipboard

Get add_draw polygon coordinates back

Open orgoca opened this issue 3 years ago • 2 comments

I'd like to know if you have any recommendation for obtaining the polygon coordinates back from the draw polygon method. So far, I am able to get the user to draw a polygon but I cant seem to find a method to retrieve the polygon coordinates (lat long) back from the map object created.

Ideally I would like to get is a list of lat-long-lists for each point the user selected in their polygon. For a 12 sided polygon I would have 12 lat-long lists inside a list, etc.

My use case is a Shiny UI in which the user can select a polygon, and then I'd use this data (lat-long list of lists) to send via a Fast API for image retrieval, inference methods and returning analytics to Shiny.

Is this possible to do and if so which method should I use?

So far I tried this to no success:

userPolygon <- google_map(location = c(34.056458, -118.247131),
                              zoom = 10,
                              # split_view = "pano",
                              event_return_type = 'list')
            
            userPolygon <- add_drawing(
                userPolygon ,
                drawing_modes = c("polygon"),
                delete_on_change = FALSE
            )
            
            results <- access_result(
                userPolygon ,
                result = c("points")
            )
            
            View(results)

orgoca avatar Jun 05 '22 01:06 orgoca

For reference, here is a Javascript implementation of the same idea. If you try the code snipet at the bottom, after drawing a polygon, you'll get a tupple of tupples containing all lat-long pairs that create the polygon. This is nice but not useful for me as I am doing my development on Shiny and not on Javascript.

https://stackoverflow.com/questions/27679291/drawing-polygon-in-google-map-using-javascript/27688473#27688473

orgoca avatar Jun 05 '22 01:06 orgoca

Thanks for the question. And the answer is straight forward: You simply need to observe the _polygoncomplete shiny method.

Here's a minimal example. After drawing the polygon you'll see the data returned to your R session (printed in the console)

library(shiny)
library(googleway)

set_key(secret::get_secret("GOOGLE"))

ui <- fluidPage(
  google_mapOutput('myMap')
)

server <- function(input, output){
  
  output$myMap <- renderGoogle_map({
    google_map(event_return_type = "list") %>%
      add_drawing()
  })
  
  observeEvent(input$myMap_map_click, {
    print(input$myMap_map_click)
  })
  
  observeEvent(input$myMap_polygoncomplete, {
    print(input$myMap_polygoncomplete)
  })
  
}

shinyApp(ui, server)

Reference:

  • Vignette article
  • you can see the method implemented here in drawing.js - as well as similar methods for _circlecomplete, _markercomplete etc

dcooley avatar Jun 05 '22 01:06 dcooley