Search code examples
rshinyr-leaflet

Mouseover behavior differs for addCircles vs. addCircleMarkers


I have a map where icons are plotted based on mouseover coordinates. When I changed my markers from addCircles() to addCircleMarkers, however, it stopped functioning. Here's a code snippet that shows the problem. Comment out the addCircles line to see how the behavior changes.

library(shiny)
library(leaflet)

#create test data
dataset <- structure(list(LATITUDE = c(37.09719065, 37.11063138, 37.1132722, 
                                 37.0749196, 37.02980937, 36.98644663, 
                                 36.94062755, 36.89560073, 36.85363852), 
                    LONGITUDE = c(283.6828216, 283.7335099, 283.7892219, 
                                  283.813835, 283.812904, 283.7935855, 
                                  283.7740784, 283.7531182, 283.7280719), 
                    ALTP = c(0.3963670049, 0.8659926907, 1.328491136, 
                             1.855292223, 2.358125869, 2.792399835, 
                             3.24886324, 3.708547366, 4.146854851)), 
                    .Names = c("LATITUDE", "LONGITUDE", "ALTP"), 
                    row.names = c(NA, 9L), 
                    class = "data.frame")


server <- function(input, output, session) {

# create base map
output$flightpath <- renderLeaflet({
leaflet() %>% addTiles() %>% setView(lng = 283.6828216,
                                              lat = 36.94062755,
                                              zoom = 10)
  })

# add markers - this is where the problem is
observe({
  leafletProxy("flightpath", data = dataset) %>%
     addCircles(weight = 6, radius = 40) 
     #addCircleMarkers(weight = 6, radius = 6)
})


# get map mouseover coordinates
map_lat_lng <- reactive ({
  req(input$flightpath_shape_mouseover)
  map_hover  <- input$flightpath_shape_mouseover
  x <- data.frame(map_hover$lat, map_hover$lng)
  colnames(x) <- c("Latitude", "Longitude")
  x
})

# add icon to map
observe({
  leafletProxy("flightpath", data = map_lat_lng()) %>%
    clearGroup("hover") %>%
    addMarkers(group = "hover")
})
}

ui <- fluidPage(leafletOutput("flightpath"))

shinyApp(ui, server)

Solution

  • You're changing it from a shape to a marker, so you need to change the object category: flightpath_shape_mouseover should become flightpath_marker_mouseover. That should fix it.