1

I have a leaflet map in an R shiny app and the map will not center and refocus on the selected location. Whats frustrating is this works with census data centroids but doesn't with my data.

I have the code below which works if i use some dummy data from census but when i use my own data (available on Github) it wont work. I am suspecting something with my data but i can't seem to understand what it might be.


#Load libraries
##########################################
library(shiny)    
library(shinyWidgets)
library(tigris)
library(leaflet)
library(rgeos)
library(rgdal)


#Get data from here - https://github.com/JoshRoll/ODOT-Projects/blob/master/Bend_Spatial_Data_2018.gdb.zip

#Count Location spatial information
##############
#Define the location where you unzipped the downloaded file
fgdb <-     "Bend_Spatial_Data_2018.gdb"
# Read the feature class
Count_Location_Info_Sp <-  readOGR(dsn=fgdb,layer= "MMCountLocations")

# Load data- Use census to use as proper spatial transformation from x/y to lat/long (Uses tigris package)
States_Sp <- states( year = "2010")
#Reproject
Count_Location_Info_Sp <-  spTransform(Count_Location_Info_Sp, CRS(proj4string( States_Sp)))  

#Create a data frame from spatial data
Data.. <- Count_Location_Info_Sp@data

#Set up User Interface
######################
ui <- fluidPage(
  titlePanel("LOcation Selector Test"),
  tabsetPanel(
    #Daily Counts Panel
    ##############
    #Hourly Counts Panel
    #######################
    tabPanel("Tab 1",
             #Call plot 
             fluidRow(
               column(3,
                      uiOutput("Location_Selector"))),
             #Location Details 
             fluidRow( 
               column(6,
                      #h4("Selected Location"),
                      leafletOutput("map_plot",height = 500))
               #Close row
             )
             #Close panel
    )
    #Close setPanel
  )
  #Page end   
)

#Set up Server
#---------------------------
server <- shinyServer(function(session,input,output){
  #Location selector
  observe({
    output$Location_Selector <- renderUI({
      selectInput(inputId = "Location_Selector",
                  label = "Select Location", multiple = FALSE,
                  choices = as.character(unique(Data..$Sub_Location_Id)),
                  selected =  unique(Data..$Sub_Location_Id)[1])
    })
  })
  #Set up starting leaflet
  ###############
  output$map_plot <- renderLeaflet({
    leaflet(Count_Location_Info_Sp) %>%
      addTiles() %>%
      addCircles(color = "black" )
    })
  #Set up proxy leaflet for updated selector
  ####################
  observe({
    dat <-  Count_Location_Info_Sp[Count_Location_Info_Sp@data$Sub_Location_Id%in%input$Location_Selector,]
    lat <-  coordinates( dat)[,1]
    long <-  coordinates(dat)[,2]
    leafletProxy("map_plot") %>% 
      clearShapes() %>%
      addTiles() %>%
      addCircles(data =dat ,color = "black" ) %>%
      setView(lng = long, lat = lat, zoom = 14)
   #Close leaflet proxy observe
  })


})
#Run App
shinyApp(ui,server)

2
  • Please post a minimum reproducible example.
    – Sada93
    Sep 3, 2019 at 4:46
  • The above code should work after downloading the spatial file form the embedded link. I tried to make an example using US Census data downloaded on the fly using the tigris package only to find the issue disappears. I then ported my data into my working census data example only to find the re-zooming issue pops back up. I am here hoping to avoid going crazy. Please let me know if there are issues with the code/data above.
    – Josh R.
    Sep 3, 2019 at 18:16

1 Answer 1

1

The Simple features (sf) package is a lot easier to work with (in my opinion) and is way more feature-rich than using sp. Here is how I would do it,

All i did was change how the data is read in using the sf package. We transform it to standatd coordinates reference frame (crs). The dataset is using a different coordinate reference frame.

And then finally, in sf you dont need to index into @data. You can treat you dataframe Count_Location_Info_Sp as a regular old dataframe (albeit with a few additional features).

#Load libraries
##########################################
library(shiny)    
library(shinyWidgets)
library(tigris)
library(leaflet)
library(rgeos)
library(geosphere)
library(sf)


#Get data from here - https://github.com/JoshRoll/ODOT-Projects/blob/master/Bend_Spatial_Data_2018.gdb.zip

#Count Location spatial information
##############
#Define the location where you unzipped the downloaded file
fgdb <-     "~/Downloads/Bend_Spatial_Data_2018.gdb"
# Read the feature class
Count_Location_Info_Sp <-  st_read(dsn=fgdb,layer= "MMCountLocations",stringsAsFactors = FALSE)
Count_Location_Info_Sp <- st_transform(Count_Location_Info_Sp, crs = "+proj=longlat +datum=WGS84")


#Set up User Interface
######################
ui <- fluidPage(
  titlePanel("LOcation Selector Test"),
  tabsetPanel(
    #Daily Counts Panel
    ##############
    #Hourly Counts Panel
    #######################
    tabPanel("Tab 1",
             #Call plot 
             fluidRow(
               column(3,
                      uiOutput("Location_Selector"))),
             #Location Details 
             fluidRow( 
               column(6,
                      #h4("Selected Location"),
                      leafletOutput("map_plot",height = 500))
               #Close row
             )
             #Close panel
    )
    #Close setPanel
  )
  #Page end   
)

#Set up Server
#---------------------------
server <- shinyServer(function(session,input,output){
  #Location selector
  observe({
    output$Location_Selector <- renderUI({
      selectInput(inputId = "Location_Selector",
                  label = "Select Location", multiple = FALSE,
                  choices = as.character(unique(Data..$Sub_Location_Id)),
                  selected =  unique(Data..$Sub_Location_Id)[1])
    })
  })
  #Set up starting leaflet
  ###############
  output$map_plot <- renderLeaflet({
    leaflet(Count_Location_Info_Sp) %>%
      addTiles() %>%
      addCircles(color = "black" )
  })
  #Set up proxy leaflet for updated selector
  ####################
  observe({
    req(input$Location_Selector)

    dat <-  Count_Location_Info_Sp[Count_Location_Info_Sp$Sub_Location_Id %in% input$Location_Selector,]
    lat <-  st_coordinates(dat)[[2]]
    long <-  st_coordinates(dat)[[1]]
    leafletProxy("map_plot") %>%
      clearShapes() %>%
      addTiles() %>%
      addCircles(data =dat ,color = "black" ) %>%
      setView(lng = long, lat = lat, zoom = 14)
    #Close leaflet proxy observe
  })


})
#Run App
shinyApp(ui,server)
3
  • This worked but I am not sure why since the data is essentially the same just different classes, spatial points data frame vs. an sf object? When i mocked this up using census data it worked an those were spatial points data frames of US States (centroids) so any idea why it would work now?
    – Josh R.
    Sep 3, 2019 at 21:07
  • I think there was an issue with the coordinate reference frame. Try converting the crs of the previous code to WGS84. Also Count_Location_Info_Sp@data$Sub_Location_Id was a factor not a character vector.
    – Sada93
    Sep 3, 2019 at 21:09
  • Thanks Sada93, i made sure to reproject into the projection you suggested and convert the factor variable to character but still it doesn't work like it does with your suggestion. It doesn't seem to be the projection or factor issue since i used the original project file (from census) used in my example and didn't convert Sub_Location_Id to character but used st_read() and st_transform() and it worked, so strange. Were you able to replicate my issue when you run it with my code. I am happy to implement your solution but now i am curious as to why loading my data using readOGR causes this?
    – Josh R.
    Sep 4, 2019 at 4:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.