rratnaya
rratnaya

Reputation: 21

Offset circles/radii produced by addCircles

I have a leaflet map (in a R Shiny application) with multiple circles/radii added as the centroid of a province.

What I would like to do is to slightly offset the circles/radii so they are not totally overlapping. Is there a way to do this? Ideally, I don't want to mess with the longitudes and latitudes, and would rather apply some overall offsetting factor. I could not find an option for this here, https://cran.r-project.org/web/packages/leaflet/leaflet.pdf.

Example code:

library(leaflet)

# added 2 markers for Delhi, India
leaflet() %>% 
  addTiles() %>%
  addCircles(lng=77.1025, lat=28.7041, 
    popup="Delhi, India", color="blue") %>% 
  addCircles(lng=77.1025, lat=28.7041,   # can this second radius be offset somehow?
    popup="Delhi, India", color="red") 

Upvotes: 1

Views: 43

Answers (1)

margusl
margusl

Reputation: 17554

I'd still consider some added jitter to be one of the easiest methods, especially when layer data is kept in a frame:

library(leaflet)
library(dplyr, warn.conflicts = FALSE)

circles <- tribble(
     ~lng,    ~lat,         ~popup, ~color,
  77.1025, 28.7041, "Delhi, India", "blue",
  77.1025, 28.7041, "Delhi, India", "red"
) 

leaflet() %>% 
  addTiles() %>%
  addCircles(
    lng = ~lng, lat = ~lat, 
    popup = ~popup, color = ~color, 
    data = mutate(circles, across(lng:lat, \(x) jitter(x, amount = 5e-5)))
  )

Leaflet screenshot, Circles, 800x200

Or perhaps opt for clustered CircleMarkers instead:

leaflet() %>% 
  addTiles() %>%
  addCircleMarkers(
    lng = ~lng, lat = ~lat, 
    label = ~popup, popup = ~popup, color = ~color, 
    clusterOptions = markerClusterOptions(),
    data = circles
  )

Leaflet screenshot, CircleMarkers, 800x200

Upvotes: 2

Related Questions