Search code examples
rshinyr-leaflet

Dynamically change leaflet map center in R Shiny


I am making an R Shiny app where users will enter their city, state, and zip code, press a button, and then their location (Lat, Lon) will become the new center of the map. The inputs are collected via this section of code in the server.R:

output$ntextCounter <- eventReactive(input$goButton, {
   citySelected <- as.character(input$city)
   stateSelected <- as.character(input$state)
   zipCodeSelected <- as.character(input$zipCode)
   location2 <- stri_detect(paste(as.character(input$city),
   as.character(input$state), as.character(input$zipCode), sep=", "), fixed = locationData$Location, opts_regex=stri_opts_regex(case_insensitive=TRUE))
   counter <<- counter + 1
   lat1 <- as.numeric(locationData[which(location2),]$latitude)
   lon1 <- as.numeric(locationData[which(location2),]$longitude)
   return(c(lat1, lon1))
})

I am able to easily view the new latitude/longitude values in the UI using:

 verbatimTextOutput("ntextCounter")

But I need to be able to pass these values, "return(c(lat1, lon1))", to the center = c(Lat, Lon) in the leaflet map in the ui.r:

leafletMap("map", "100%", 365,
    initialTileLayer = "http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
    initialTileLayerAttribution = HTML('&copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>'),
    options=list(center = c(38.25, -93.85), zoom = 4, maxBounds = list(list(1, -180), list(78, 180))
    )),

I have an initial map center at c(38.25, -93.85), but ultimately I want to be able to pass it changing values from ntextCounter. I'm not sure if this is a scoping issue or what but I need help getting the new lat/lon values into the leaflet map center.


Solution

  • It seems you are creating your leaflet on the ui-side. If you want it to be responsive to inputs you've got to do that on the server side with renderLeaflet.

    Your coordinates could be stored in a reactiveValues and you'd update them with a observeEvent:

    location <- reactiveValues(lat = 38.25, lon = -93.85)
    observeEvent(input$goButton, {
               city <- as.character(input$city)
               state <- as.character(input$state)
               zipCode <- as.character(input$zipCode)
               newloc <- stri_detect(paste(city, state, zipCode, sep=", "), 
                                        fixed = locationData$Location, 
                                        opts_regex=stri_opts_regex(case_insensitive=TRUE))
              location$lat <- as.numeric(locationData[which(newloc),]$latitude)
              location$lon <- as.numeric(locationData[which(newloc),]$longitude)
    })