2

Problem: We have an area divided into regions, which are further divided into subregions.

Our Task : Create a map of the area, such that when we hover over a point,it should highight the boundary of the region and the tooltip should show the name of the subregion and region.

Solution 1 : Create a shapefile of the regions. Now when we hover over a point it will highlight the boundary of the region but the tooltip will not show the name of the corresponding subregion,it will show the name only of the region.

This is how I can do it with leaflet in R:

library(tigris)
library(dplyr)
library(leaflet)

m1 <- states()
m2 <- counties()

head(m1@data)
head(m2@data)

#Map 1

labels <- sprintf("State name : %s",
m1@data$NAME) %>% lapply(htmltools::HTML)

leaflet(data = m1) %>%
addPolygons(
highlight = highlightOptions(
weight = 5,
color = "#666",
dashArray = "",
fillOpacity = 0.7,
bringToFront = TRUE),
label = labels)

Solution 2 : Create a shapefile of the subregions. Now when we hover over a point it will highlight the boundary of the subregion and NOT the boundary of the region, but it will show the name of the corresponding region and subregion.

This is how I can do it with leaflet in R:

#Map 2

# Keep statefp and the name of the State.
m3 <- m1@data[,c(3,7)]

names(m3)[2] <- "StateName"

m2@data <- left_join(m2@data,m3,by = c("STATEFP"))

labels <- sprintf("State name : %s<br>County Name : %s",
m2@data$StateName,m2@data$NAME) %>% lapply(htmltools::HTML)


leaflet(data = m2) %>%
addPolygons(
highlight = highlightOptions(
weight = 5,
color = "#666",
dashArray = "",
fillOpacity = 0.7,
bringToFront = TRUE),
label = labels)

Query : How can we mix 1 and 2 ? how can we display the boundary of the region but the name of the subregion (and region) when we hover over a point ?

Thanks to Michael Bird for recommending to use tigris.

user2338823
  • 501
  • 1
  • 3
  • 16
  • An easy way to make a reproducible example would be to use the `tigris` package and it's `counties()` function, you can use states as a region, and Counties as a subregion. – Michael Bird Feb 22 '18 at 10:15
  • There is a similar query [here](https://stackoverflow.com/questions/32216819/zooming-into-state-to-view-zipcode-using-r-leaflet) – user2338823 Mar 13 '18 at 06:25

0 Answers0