count the number of elements within a leaflet marker

Good afternoon, I am new to the forum and I need help, I want to know if in some way the count of the elements that are inside a circular marker can be made.

I attach a reference image of how I have at the moment.

the red dots inside the blue marker are the ones that need to be counted, I would appreciate any help, thanks

Welcome to the forum! (and it is not afternoon anymore over here in Europe, not that it matters)

Leaflet is a presentation tool, not really meant for counting things (it is meant for drawing maps).

But if you have access to the underlying data structures you should have two separate objects, hopefully in {sf} package format. One should be of polygon geometry type (the blue circle) and the other a bunch of points.

To get the intersection of the two objects you may consider runing sf::st_join() on them, specifying that you want an inner join (both datasets filtered). This is done by setting the parameter left = FALSE (meaning the join is not left, it is inner). The it is only the matter of counting rows.

muchas gracias por la pronta respuesta y la aclaración al respecto sobre el tema de Leaflet y por la posible solución, si alguien tiene alguna formula con la cual se podría trabajar les agradecería inmensamente

Oki, consider this code

What it does is:

  • produces a data frame of 3 semi random North Carolina locations (just because I like NC)
  • creates a buffer of 2 arc degrees around Greensboro; two of the locations will be in and one out
  • creates a leaflet map to visually check the expected count (two out of three red points are in)
  • does the actual counting by spatially joining the buffer and cities objects, and counting the number of rows

# three semi random cities in NC
cities <- data.frame(name = c("Raleigh", "Greensboro", "Wilmington"),
                  x = c(-78.633333, -79.819444, -77.912222),
                  y = c(35.766667, 36.08, 34.223333)) %>% 
  sf::st_as_sf(coords = c("x", "y"), crs = 4326)

# buffer of 2 arc degrees around Greensboro
buffer <- sf::st_buffer(cities[2, ], 2)

# a leaflet call, looking sorta kinda like yours
leaflet() %>% 
  addProviderTiles("Stamen.Toner") %>% 
  addPolygons(data = buffer) %>% 
  addCircleMarkers(data = cities, 
                   color = "red",
                   fillOpacity = 2/3,
                   stroke = F)

# this is the action! :)
count <- sf::st_join(cities, buffer, left = F) %>% 

1 Like

This topic was automatically closed 54 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.