Jacob Nordstrom
Jacob Nordstrom

Reputation: 159

Showing two labels over a polygon in leaflet in R

I am mapping out zip code areas in leaflet and coloring the polygon based on the Dealer.

Dealer Zipcodes  geometry
A      32505     list(list(c(.....)))
B      32505     ....

This code is used to create the colors, labels, and the map.

factpal <- colorFactor(topo.colors(5), data$Dealer)

labels <- paste0("Zip Code: ",data$Zipcodes, ", Dealer: ", data$Dealer)

leaflet(data) %>% 
  addTiles()   %>% 
  addPolygons( color = ~factpal(Dealer),),
              label = labels) %>% 
  leaflet.extras::addSearchOSM(options = searchOptions(collapsed = FALSE)) %>% 
  addLegend(pal = factpal, values  = ~Dealer, 
            opacity = 0.7, 
            position = "bottomright")

When the zip code (and thus the geometry) are the same between two dealers, only one label is visible, though it is clear colors are overlapping. All I want is for that label to somehow show the info for both dealers in that zip code. Please let me know if there is code missing you need, or clarification needed.

enter image description here

Upvotes: 1

Views: 457

Answers (1)

stefan
stefan

Reputation: 125373

Not sure whether you could have multiple tooltips but to show all Dealers in the tooltip you could change your labels such that they include all dealer names per zip code, e.g. making use of dplyr you could do:

library(leaflet)
library(dplyr)

factpal <- colorFactor(topo.colors(5), data$Dealer)

data <- data %>% 
  group_by(Zipcodes) %>% 
  mutate(labels = paste(Dealer, collapse = ", "),
         labels = paste0("Zip Code: ", Zipcodes, ", Dealer: ", labels))

leaflet(data) %>%
  addTiles() %>%
  addPolygons(
    color = ~factpal(Dealer),
    label = ~labels,
    weight = 1
  ) %>%
  # leaflet.extras::addSearchOSM(options = searchOptions(collapsed = FALSE)) %>%
  addLegend(
    pal = factpal, values = ~Dealer,
    opacity = 0.7,
    position = "bottomright"
  )

enter image description here

DATA

nycounties <- rgdal::readOGR("https://eric.clst.org/assets/wiki/uploads/Stuff/gz_2010_us_050_00_20m.json")
nycounties_sf <- sf::st_as_sf(nycounties)

nycounties_sf_n <- nycounties_sf %>%
  filter(STATE == "01") %>%
  select(Zipcodes = COUNTY, geometry)
data <- list(
  A = sample_n(nycounties_sf_n, 40),
  B = sample_n(nycounties_sf_n, 40),
  C = sample_n(nycounties_sf_n, 40),
  D = sample_n(nycounties_sf_n, 40)
)
data <- purrr::imap(data, ~ mutate(.x, Dealer = .y))
data <- do.call("rbind", data)

Upvotes: 2

Related Questions