Search code examples
rshinyr-leaflet

Long/Lat data points not found though they are provided for interactive map in Shiny


I'm trying to print to an interactive map using filters in the data however, I'm getting an error saying that the longitude and latitude points are not provided.

I've provided a copy of my code and a sample of the data.

library(shiny)
library(leaflet)
library(dplyr)
library(stringr)
library(ggplot2)

#import data
data <- structure(list(VictimSex = structure(c(2L, 2L, 4L, 4L, 2L), .Label = c("", 
                                                                       "F", "H", "M", "N", "X"), class = "factor"), Long = c("34.0508", 
                                                                                                                             "33.8542", "34.1052", "34.0255", "33.9997"), Lat = c("-118.2731", 
                                                                                                                                                                                  "-118.2905", "-118.3252", "-118.3548", "-118.2827")), row.names = c(NA, 
                                                                                                                                                                                                                                                      5L), class = "data.frame")


#Define UI ----
ui <- fluidPage(
  titlePanel("Interactive Los Angeles Traffic COllision"), 
  sidebarLayout(
    sidebarPanel(
      checkboxGroupInput("Gender", h3("Gender"), choices = list("F", "M"), selected = "Female")
    ),
    mainPanel(leafletOutput("map", "100%", 500), 
              plotOutput("bar"))
  )
)

#Define Server logic ---- 
server <- function(input, output, session) {
  filtered <- reactive ({
    if (is.null(input$Gender)){
      return(NULL)
    }
    data %>% filter(VictimSex %in% input$Gender)
  })

  output$map <- renderLeaflet({
    leaflet()%>%
      addProviderTiles("CartoDB") %>%
      addCircleMarkers(data = filtered(), radius = 2)
  })
}

#Run the app ----
shinyApp(ui, server)

The error I'm getting is: Point data not found; please provide addCircleMarkers with data and/or lng/lat arguments


Solution

  • There are 3 issues in your code.

    1 - When input$Gender is not set, filtered reactive returns NULL.

    Fix : Add a req a the beginning of the function so it is not triggered until the input is set.

    req(input$Gender)
    

    An alternative would be to return full dataset if no filter is active. Just replace return(NULL) by return(data)

    2 - The lat/long data is in text while it should be numeric.

    Fix : You can convert it by using as.numeric() at the beginning of the code

    data$Lat <- as.numeric(data$Lat)
    data$Long <- as.numeric(data$Long)
    

    3 - Lat and Long are inverted.

    Fix : You can exchange the columns value

    tmpLat <- data$Long
    data$Long <- data$Lat
    data$Lat <- tmpLat