Search code examples
rshinyleafletgeosphere

How to calculate distance between 2 points with leaflet, geosphere, and R shiny


This is a simplified working representation of my code. I have two collections of locations of points. One is automobiles and the other is dealers. There is a slider of distance in miles. If a user clicks on the dealer location and selects the distance on the slider, only the auto locations within the distance from the dealer selected will be visible on the map. I have a another picklist of city which works well. However, when I pick a dealer the display goes to an error and I get Warning: Error in .pointsToMatrix: points should be vectors of length 2, matrices with 2 columns, or inheriting from a SpatialPoints object* I have looked at some other questiosn with the same error bu they are very different problems. Thanks in advance !



library(shiny)
library(DT)
library(ggplot2)
library(dplyr)
library(leaflet)
library(geosphere)
r = 3959

City <- c("Boston","Boston", "Boston", "Lowell","Lowell", "Lowell","Worcestor", "Worcestor","Worcestor","Springfield","Springfield","Springfield")
lat <- c(42.35, 42.355, 42.345, 42.63,42.625,42.635,42.27,42.265,42.275, 42.1,42.105,42.095)
lng <- c(-71.05,-71.045,-71.055,-71.316,-71.315,-71.317,-71.79,-71.785,-71.795,-72.6,-72.595,-72.605)

MassLocations <- data.frame(City, lat,lng)
# MassLocations has 4 cities with 3 locations each


Dealer <- c("West","Central", "East")
lat <- c(42.1, 42.0, 42.2)
lng <- c(-72.5,-71.8, -71.1)

MassDealers <- data.frame(Dealer, lat, lng)
#massDelaers has 3 dealers in West, Central, and East


ui <- fluidPage(titlePanel("Mass mpg by location"),
                
                # Create a new Row in the UI for selectInputs
                fluidRow(
                    column(4,
                           selectInput("Dealer",
                                       "Dealer:",
                                       c("All",
                                         unique(as.character(MassDealers$Dealer)))),
                           sliderInput("Distance", 
                                       "Distance from Dealer:", 
                                       min = 1,
                                       max = 100, 
                                       value = 100),
                           selectInput("City",
                                       "City:",
                                       c("All",
                                         unique(as.character(MassLocations$City))))
                    ),
                            ),
                # Create a new row for the table.
                leafletOutput("map01"),
                DT::dataTableOutput("table")
                
)


    

# Define server logic required to draw a histogram
server <- function(input, output) {
    
    
            # Filter data based on selections
            dataShow <- reactive({
                data <- MassLocations
                Ddata <- MassDealers
                if (input$Dealer != "All") {
                    Ddata <- Ddata[Ddata$Dealer == input$Dealer]
                    data$Distance <- (distHaversine((cbind(Ddata$lng,Ddata$lat)),cbind(data$lng,data$lat)))/1600
                    data <- data[data$Distance < input$Distance, ]
                }
                
                
                
                
                if (input$City != "All") {
                    data <- data[data$City == input$City, ]
                }
                data
            })
            
            # Display
            output$table <- DT::renderDataTable(
                DT::datatable(dataShow()))      
        
        
        
        
        # map
        output$map01 <- renderLeaflet({
            #pal <- colorNumeric("YlOrRd", domain=c(min(quakes$mag), max(quakes$mag)))
            qMap <- leaflet(data = (dataShow())) %>% 
                addTiles() %>%
                addCircles(radius =3, color="red")
            qMap
        })
        
} 
        
# Run the application 
shinyApp(ui = ui, server = server)



Solution

  • In line 63, you missed a comma, so Ddata data frame fail to respond to the subset operation. This is a simple fix as follows.

      # Filter data based on selections
      dataShow <- reactive({
        data <- MassLocations
        Ddata <- MassDealers
        if (input$Dealer != "All") {
          Ddata <- Ddata[Ddata$Dealer == input$Dealer, ]
          data$Distance <- (distHaversine((cbind(Ddata$lng,Ddata$lat)),cbind(data$lng,data$lat)))/1600
          data <- data[data$Distance < input$Distance, ]
        }