How to set the current location as a reactive value in shiny to use it in leafletproxy?

Viewed 13

Hello and thanks for reading me. I am currently working on an app to get the current location and I would like to put it on a point in a leaflet map, but it is giving me the error: Error in validateCoords: addCircleMarkers requires non-NULL longitude/latitude values and I don't understand why this happens , since when generating that information with a verbatimTextOutput() it works correctly, but when using a proxy in leaflet it gives me an error. Does anyone know why this happens? Thank you very much for the help, the code is as follows:

library(shiny)
library(leaflet)
library(dplyr)

script <- '
      $(document).ready(function () {
        navigator.geolocation.getCurrentPosition(onSuccess, onError);
              
        function onError (err) {
          Shiny.onInputChange("geolocation", false);
        }
              
        function onSuccess (position) {
          setTimeout(function () {
            var coords = position.coords;
            console.log(coords.latitude + ", " + coords.longitude);
            Shiny.onInputChange("geolocation", true);
            Shiny.onInputChange("lat", coords.latitude);
            Shiny.onInputChange("long", coords.longitude);
          }, 1100)
        }
      });
              '





shinyApp(
  ui = fluidPage(
    
    titlePanel("Using Geolocation"),
    
    actionButton("ejemplo", "xd"),
    
    uiOutput("xd"),
    fluidRow(column(width = 2,
                    leafletOutput("map"))
    )
  ),
  server = function(input, output, session) {
    
    output$map <- renderLeaflet({
      
      leaflet() |> 
        setView(-93.65, 42.0285, zoom = 17) |> 
        addProviderTiles(provider = providers$CartoDB.DarkMatter)
      
    })
    
    observeEvent(input$ejemplo,{
      
      data <- reactive({
        
        data.frame(
          lat = input$lat,
          lng = input$long
        )
      })
      
    })
    
    
    observeEvent(input$ejemplo,{
      
      req(data())
      
      if (nrow(data()) >0 ){
        
        leafletProxy("map", session) |> 
          addCircleMarkers(
            lat = data()$lat,
            lng = data()$lat
          )
      }
    
      
    })
    
    observeEvent(input$ejemplo,{
      
      output$xd <- renderUI(tags$script(script))
      
    })
    
    output$lat <- renderPrint({
      input$lat
    })
    
    output$long <- renderPrint({
      input$long
    })
    
  }
)
0 Answers
Related