Sizing leaflet icons based on distance rather than pixels?

I would like to determine the size of leaflet icons based on lat/long distance rather than pixels. How can I accomplish this with the leaflet R package?

Ideally, I would like markers to fit within sf polygons. I can determine the lat/long distance of the largest marker that would fit within the polygon if located at the centroid, but I cannot convert this lat/long distance value to pixels.

Reproducible Example:

Loading in packages, data, and inscription function.


# creates inscribed circle on any polygon
inscribed_circle <- function(poly) {
  # Get centroid of polygon
  centroid <- sf::st_centroid(poly)

  # Get nearest point
  radius <- sf::st_length(sf::st_nearest_points(poly, centroid, pairwise = TRUE))

  # Create circle as a point with a buffer around it
  circle <- sf::st_buffer(centroid, radius)


# loading spatial data
nc <- st_read(system.file("shape/nc.shp", package="sf")) |>
  sf::st_transform("+proj=longlat +datum=WGS84")

Selecting the first polygon in the nc dataset.

Determining the distance between the centroid of the polygon and the closest point on the polygon. Creating an inscribed circle with a radius equal to this distance and plotting.

Adding a marker that is scaled based on the radius of the inscribed circle. Marker size is in pixels and circle radius is in meters (lat/long calculation). Not sure how to do this conversion.

polytest <- nc[1,15]

# creating geometry of inscribed circle
inscribed <- inscribed_circle(polytest)

# calculating size of inscribed polygon
polytest$centroid <- sf::st_centroid(polytest)
iconsize_max <- sf::st_length(sf::st_nearest_points(polytest$geometry,
                                                        pairwise = TRUE))

# scaling the marker relative to the inscribed polygon size
icons <- leaflet::icons(
  iconUrl = c(""),
  iconWidth = iconsize_max/100, # scaling by 100 otherwise icon would not be visible
  iconHeight = iconsize_max/100

# Creating leaflet map with polygons and markers
leaflet::leaflet() |>
  leaflet::addPolygons(data = polytest,
              fillOpacity = 0,
              color = "red",
              weight = 1) |>
  leaflet::addPolygons(data = inscribed,
                       fillOpacity = 0,
                       color = "blue",
                       weight = 1) |>
  leaflet::addMarkers(data = polytest$centroid,
                      icon = icons)

This topic was automatically closed 42 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.