Restrict the viewable part of a Leaflet tile to a polygon area - r

I am learning how to use R and Leaflet. I am almost done making a map using California counties, but I don't like that I can see other states in the map. I would like to white out the map around my polygon (the counties). I saw a similar problem resolved elsewhere but I don't know enough to apply what was said there to my code. Could someone check this code out and suggest what I need to add?
If you scroll to the bottom of this link you'll see what I am trying to do. http://rpubs.com/stefanya/127436
The code I am using is:
#loading shapefile
counties <- readOGR("./shapefiles", layer="cb_2014_us_county_20m")
#filtering for only california
counties <- subset(counties, counties#data$STATEFP=="06")
#making a leaflet map of california counties
leaflet() %>% addTiles() %>% addPolygons(data=counties)
#merging the data into this shapefile
counties#data = data.frame(counties#data, sumByCounty[match(counties#data[,"NAME"], sumByCounty[,"NAME"]),])
#set color palette
colorRamp <- colorRamp(c("#2c7fb8","#7fcdbb","#edf8b1"), interpolate = "spline")
palette <- colorNumeric(colorRamp, counties#data$progress)
leaflet() %>% addProviderTiles("Stamen.TonerLite") %>%
addPolygons(
weight= 2,
stroke = TRUE,
fillOpacity = .65,
data=counties,
color = ~palette(progress),
popup = ~paste("<strong>County:</strong>",NAME,
"<br>",
"<strong>Total Responses:</strong>",sumByCounty,
"<br>",
"<strong>Complete:</strong>",progress,"<strong>%</strong>")
) %>% addLegend(title = "Response <br> Goal Met", pal = palette, values = counties#data$progress, bins=5, opacity = 1, position="topright", labFormat = labelFormat(suffix = '%'))

Create a polygon with with two rings, the first with geometry of the entire earth (or your view's bounds), the second with the geometry of California:
[
// World
[[90,-180], [90,180], [-90,180], [-90,-180]],
// California
[[42.006186,-123.233256],[42.011663,-122.378853],[41.995232,-121.037003],[41.995232,-120.001861],[40.264519,-119.996384],[38.999346,-120.001861],[38.101128,-118.71478],[37.21934,-117.498899],[36.501861,-116.540435],[35.970598,-115.85034],[35.00118,-114.634459],[34.87521,-114.634459],[34.710902,-114.470151],[34.448009,-114.333228],[34.305608,-114.136058],[34.174162,-114.256551],[34.108438,-114.415382],[33.933176,-114.535874],[33.697668,-114.497536],[33.54979,-114.524921],[33.40739,-114.727567],[33.034958,-114.661844],[33.029481,-114.524921],[32.843265,-114.470151],[32.755634,-114.524921],[32.717295,-114.72209],[32.624187,-116.04751],[32.536556,-117.126467],[32.668003,-117.24696],[32.876127,-117.252437],[33.122589,-117.329114],[33.297851,-117.471515],[33.538836,-117.7837],[33.763391,-118.183517],[33.703145,-118.260194],[33.741483,-118.413548],[33.840068,-118.391641],[34.042715,-118.566903],[33.998899,-118.802411],[34.146777,-119.218659],[34.26727,-119.278905],[34.415147,-119.558229],[34.40967,-119.875891],[34.475393,-120.138784],[34.448009,-120.472878],[34.579455,-120.64814],[34.858779,-120.609801],[34.902595,-120.670048],[35.099764,-120.631709],[35.247642,-120.894602],[35.450289,-120.905556],[35.461243,-121.004141],[35.636505,-121.168449],[35.674843,-121.283465],[35.784382,-121.332757],[36.195153,-121.716143],[36.315645,-121.896882],[36.638785,-121.935221],[36.6114,-121.858544],[36.803093,-121.787344],[36.978355,-121.929744],[36.956447,-122.105006],[37.115279,-122.335038],[37.241248,-122.417192],[37.361741,-122.400761],[37.520572,-122.515777],[37.783465,-122.515777],[37.783465,-122.329561],[38.15042,-122.406238],[38.112082,-122.488392],[37.931343,-122.504823],[37.893004,-122.701993],[38.029928,-122.937501],[38.265436,-122.97584],[38.451652,-123.129194],[38.566668,-123.331841],[38.698114,-123.44138],[38.95553,-123.737134],[39.032208,-123.687842],[39.366301,-123.824765],[39.552517,-123.764519],[39.831841,-123.85215],[40.105688,-124.109566],[40.259042,-124.361506],[40.439781,-124.410798],[40.877937,-124.158859],[41.025814,-124.109566],[41.14083,-124.158859],[41.442061,-124.065751],[41.715908,-124.147905],[41.781632,-124.257444],[42.000709,-124.213628],[42.006186,-123.233256]]
]
Example on Plunker: http://embed.plnkr.co/ZWzuxz/preview

Related

For Leaflet in R, can you add a button that adds and removes polygons for each map layer?

If we just take a standard leaflet map like the one below:
library(leaflet)
library(maps)
mapStates = map("state", fill = TRUE, plot = FALSE)
leaflet(data = mapStates) %>% addTiles() %>%
addPolygons(fillColor = topo.colors(10, alpha = NULL), stroke = FALSE)
Is there a way to add a button that adds and removes certain polygons? For example, if the map above contained several layers (i.e. uninsured rates & average age), I would want a button or toggle switch that would allow a user to add and remove all states that begin with "a" (silly example). So instead of having 4 layers (two with those statistics across all states and two with those statistics across the states that do not begin with "a"), I would only have two layers and a button.
My caveat is that it needs to be exportable in .html format, which means I cannot deploy a shiny solution.
Perhaps there's an addEasyButton solution?
You will need to add a unique identifier in the group parameter of the addPolygons() function, then pipe to addLayersControl(), per https://rstudio.github.io/leaflet/showhide.html
I am not able to fully provide code, since I don't have your mapStates data, but here's an attempt
library(leaflet)
library(maps)
mapStates = map("state", fill = TRUE, plot = FALSE)
leaflet(data = mapStates) %>% addTiles() %>%
addPolygons(fillColor = topo.colors(10, alpha = NULL), stroke = FALSE, group = "stateShape") %>%
addLayersControl(overlayGroups = c("stateShape"))

Leaflet in R: automatically setting view according to one layer

I am making some maps in Leaflet in R, and the maps consist of a polygon layer as well as a layer of markers. The polygon usually covers a larger area than the markers, but I want to zoom specifically to the marker area.
I know I can manually specify lat/longs and zoom level, but I don't want to do that because this code will generate a lot of different maps covering different subsets of my dataset (or on different datasets).
Here's a simplified version of the code that generates the map. I don't think this necessarily requires a full reprex to answer the question but can do so if necessary.
addProviderTiles(providers$CartoDB.Positron, group = "Basemap") %>%
addPolygons(data = seat_boundary, fillColor = "white", fillOpacity = 0.0, weight = 1.5, opacity = 0.6, color = "red", group = "Seat boundary") %>%
addCircleMarkers(data = formalvotes_by_booth_subarea, fillColor = ~subarea_pal(sub_areas), lng=~longitude, lat=~latitude, radius = ~circle_size, fillOpacity = 1, color = 'white', opacity = 1, weight = 1.2, popup = ~popup) %>%
addLegend(pal = subarea_pal, values = formalvotes_by_booth_subarea$sub_areas, opacity = 1)```
I also think I might be able to half-solve this problem by averaging the max and min latitude and max and min longitude in the markers dataset to come up with a central point to focus the map on, but it wouldn't ensure the zoom would be correct (indeed I'm not sure if you can set the lat/long and not set the zoom).
Thanks!
Have you tried fitBounds?
Starting from what you have posted, I would first get the bbox coordinates of your markers:
library(sf)
bounds <- markers %>%
st_bbox() %>%
as.character()
Then passing them into the fitBounds function:
library(leaflet)
leaflet %>%
addPolygons(data = polygons) %>%
addCircleMarkers(data = markers) %>%
fitBounds(bounds[1], bounds[2], bounds[3], bounds[4])

Leaflet R performance issues with large map

I'm wondering if anyone else has experienced similar issues when plotting a large number of markers and polygons using leaflet package in R. This is what it normally should look like:
However, when I zoom in/out of the map, the polygons and markers are clearly out of place (or you can say the base map does not adjust properly). An example is included below:
I would not have this issue when I plotted a smaller area or few markers. I'm wondering if there is a way to improve the performance. Many thanks in advance for your help!
A sample of my code is included below:
map1 <- leaflet() %>%
addProviderTiles("CartoDB.Positron") %>%
addPolygons(data = data_merged, group="Default",
fillColor = ~pal(minority_population), color = "orange",
fillOpacity = 0.7,weight = 1, smoothFactor = 0.2, popup = popup) %>%
addMarkers(data = branches_temp, ~long, ~lat,
popup=~name_branch, group="Branch Locations",
icon=icons(iconUrl = "./data/bank_blue_marker.png",iconWidth=20, iconHeight=20))

Loading SpatialPolygonsDataFrame with Leaflet (for R) doesn't work

first of all I'm new to R so please bear with me.
What I'm eventually trying to accomplish is to show an interactive map of Amsterdam with Leaflet. For that I'm using RGDAL to read shapefiles.
This link contains the shapefiles of amsterdam.
I'm using the following code to read the shapefiles and to show the map.
amsterdam <- readOGR(".", layer = "sd2010zw_region", verbose = FALSE)
leaflet(amsterdam) %>%
addProviderTiles("CartoDB.Positron", options= providerTileOptions(opacity = 0.99)) %>%
addPolygons(
stroke = FALSE, fillOpacity = 0.5, smoothFactor = 0.5
)
What I get is the map from CartoDB.Positron but not the 'polygonmap' as the second layer. What I get is a SpatialPolygonsDataFrame containing all sorts of data.
When I use the plot method on the other hand I get the map of Amsterdam
plot(amsterdam, axes=TRUE, border="gray")
But I don't want to use plots, I want to use Leaflet :)
What am I doing wrong here?
The problem is the projection. You need to project your data to longlat using spTransform from either rgdal or sp. Also, provide your SpatialPolygonsDataFrame in the addPolygons() call.
library(leaflet)
library(rgdal)
amsterdam <- readOGR(".", layer = "sd2010zw_region", verbose = FALSE)
ams_ll <- spTransform(amsterdam, CRS("+init=epsg:4326"))
leaflet() %>%
addProviderTiles("CartoDB.Positron", options= providerTileOptions(opacity = 0.99)) %>%
addPolygons(data = ams_ll,
stroke = FALSE, fillOpacity = 0.5, smoothFactor = 0.5
)
Tip: Don't forget to add the data = ... variable name in addPolygons() call.
This does not work:
leaflet() %>%
addTiles() %>%
addPolygons(ams_ll)
This works:
leaflet() %>%
addTiles() %>%
addPolygons(data = ams_ll)
I have spent a few hours looking for a solution, hopefully this will be helpful for others.

Roads and Radius Circles in choroplethr, ggmap, or ggplot2

I'm using library(choroplethr) for some market analysis and I have some questions about making my county_choropleth and either overlaying it on top of a ggmap() or using reference_map=TRUE in my code. What I'm trying to do is take my county choropleth and place state interstates/highways and draw circles/radii on top of it.
What I currently have is this:
library(choroplethr)
data <- Data.frame(County.FIPS = c(19153,19163,19153,19153,19153,19153,19153,19113,19007,19169), Score=c(812.6,769.5,757.9,757.2,722.6,712.4,69727,690.2,64539,642.5)
county <-aggregate(data$Score~data$County.FIPS,data=data,sum)
colnames(county) <- c("region", "value")
mp <- county_choropleth(county, state_zoom=c("iowa"), num_colors = 1) +
theme(legend.position="none")+
scale_fill_gradient2("Score",
high = "dark green",
low = "red",
na.value = "grey90",
breaks = pretty(county$value, n = 10),
label = scales::dollar_format())
...which gives me this plot.
From here, what I would like to do is overlay the main interstates in the state of Iowa on top of my map and also create some radius circles to show distance from certain cities in miles. I would like it to take elements from this map and ideally incorporate them into my choroplethr map because, in my opinion, it looks a lot cleaner than in this example:
I used this code to retrieve the second map:
library(ggmap)
test<-get_map(location = c(lon=-93.57217,lat=41.67269), maptype="roadmap",source="google",zoom=7,scale="auto")
yup <- data.frame(lon=c(-93.57217,-95.87509), lat=c(41.67269,41.23238),score=c(1,1))
ggmap(test) + stat_density2d(aes(x = lon, y = lat, fill = score,alpha=score),
size = 2, bins = 2, data = yup, geom = "polygon") +
theme(legend.position="none")
My main problem with using reference_map=TRUE in the choroplethr library is that it grays out labels, roads, etc. when I place my county_choropleth on top of it. e.g.,
So, is there an easy workaround for including roads and drawing circles on a map or do I need to abandon using choroplethr and move to ggmap, ggplot2 or something else? I also have been able to locate the Iowa DOT shapefiles for roads on their website, so that is an option to include, but I don't know how specifically to only ask it to use main interstates/highways when plotting and reading into R.
Here is my "ideal" MS Paint solution to this problem:
Thank you in advance for any and all help and please let me know if you have any clarification questions that need to be answered in order to help!
For those who stumble upon this later. I was able to achieve what I was hoping to do by changing libraries to leaflet and tigris.
I plan on making final tweaks for personal use, but here is the code used:
library(tigris)
library(leaflet)
data <- data.frame(County.FIPS = c(19153,19163,19153,19153,19153,19153,19153,19113,19007,19169), Score=c(812.6,769.5,757.9,757.2,722.6,712.4,69727,690.2,64539,642.5))
county <-aggregate(data$Score~data$County.FIPS,data=data,sum)
colnames(county) <- c("GEOID", "Score")
IA_counties <- counties(state="IA", cb=TRUE, resolution ="20m")
IA_merged <- geo_join(IA_counties,county,"GEOID", "GEOID")
pal <- colorQuantile("Greens",NULL,n=3)
popup <- paste0("Profitability: ", as.character(IA_merged$Score))
yup2 <- data.frame(lon=c(-93.57217,-95.93779),lat=c(41.67269,41.25861),score=c(1,1))
leaflet() %>%
addProviderTiles("Esri.WorldStreetMap") %>%
addLegend(pal = pal,
values = IA_merged$Score,
position = "bottomright",
title = "County Profitablity: ") %>%
addCircles(lng=yup2$lon, lat=yup2$lat,weight=1,fillOpacity=0.05,color="red",
radius = 96560) %>%
addCircles(lng=yup2$lon, lat=yup2$lat,weight=1,fillOpacity=0.025,color="blue",
radius = 193121) %>%
addPolygons(data = IA_counties,
fillColor = ~pal(IA_merged$Score),
fillOpacity = 0.15,
weight = 0.2,
popup = popup)

Resources