I am brand new to shiny and leaflet and need your help, please. I want to build an app in r that shows in a leaflet map the geolocation of the user. It seems easy, however I couldn't deploy the app.
I started with an example code to build a map using leaflet and shiny that runs well:
library(shiny)
library(leaflet)
library(htmlwidgets)
ui <- fluidPage(
leafletOutput("mymap")
)
server <- function(input, output, session) {
output$mymap <- renderLeaflet({
leaflet() %>%
addTiles() %>%
setView(lng = -48.465, lat = -27.55, zoom = 12) %>%
addMarkers(lng = -48.465, lat = -27.55)
})
}
shinyApp(ui, server)
Then, I tried to add some lines of JS code (I find here) to have access to the geolocation of the user. These code lines are below:
tags$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)
}
});
')
On my last try, I executed:
library(shiny)
library(leaflet)
library(htmlwidgets)
ui <- fluidPage(
tags$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)
}
});
'),
leafletOutput("mymap")
)
server <- function(input, output, session) {
# Observador reativo para os inputs de geolocalização
observe({
# Se geolocation for TRUE, renderize o mapa
if (input$geolocation) {
# Cria um mapa com a biblioteca leaflet
leaflet() %>%
addTiles() %>%
setView(lng = input$long, lat = input$lat, zoom = 12) %>%
addMarkers(lng = input$long, lat = input$lat) %>%
# Renderize o mapa
renderLeaflet(output, "mymap")
}
})
}
shinyApp(ui, server)
However, it does not work. I got the following message:
Warning: Error in if: argument is of length zero
47: observe [#5]
46: <observer>
3: runApp
2: print.shiny.appobj
1: <Anonymous>
Can you help me? What is wrong? Thank you in advance; Marcio.