问题
I am working on an interactive map with the R package "leaflet".
I would like to change automatically the visible layers depending on the zoom level.
For example, I would like to have a polygon layer disappearing when zooming in, replaced by a points layer. Something like this : https://tree-map.nycgovparks.org/
I've been trying many different tricks and exploring in details the help from the "leaflet" and "leaflet.extras" packages, but could not find anything doing that.
I also found something straight from leaflet but it does not seem to be reproducible under R : Setting zoom level for layers in leaflet
I tried to use the options minZoom and maxZoom from markerOptions, but it does not appear to do what I want.
Here is my code for this example :
require(spData)
require(leaflet)
require(sf)
# loading shapes of countries from the package spData
data(world)
world <- st_read(system.file("shapes/world.gpkg", package="spData"))
# creating a sf objet with oceanian countries boundaries
oceania <- world[world$continent=="Oceania",]
#loading points events from the quakes dataset
data(quakes)
#Creating a leaflet objet with points and polygons
leaflet() %>%
addProviderTiles(providers$CartoDB.Positron) %>%
addCircleMarkers(lng=quakes$long,
lat=quakes$lat,
col="blue",
radius=3,
stroke=FALSE,
fillOpacity = 0.7,
options = markerOptions(minZoom=15, maxZoom=20)) %>%
addPolygons(data= oceania,
col="red")
It gives me the expected layers with the expected background from openstreetmap, but the minZoom and maxZoom arguments don't change anything. I expected the points layer to only appear between zoom levels 15 and 20, but it does not work like this, it seems.
Image from the viewer
回答1:
The group
argument in most of the "addElement()" type functions becomes very important for managing how a map works. I recommend it, and you can do a lot of neat stuff by carefully thinking about how you group your data.
By calling groupOptions()
, you can set the zoom levels for whatever layers you like. Below I have added the zoom levels you specified, but feel free to play around with it to adjust it to your needs.
#Creating a leaflet object with points and polygons
leaflet() %>%
addProviderTiles(providers$CartoDB.Positron) %>%
addCircleMarkers(lng=quakes$long,
lat=quakes$lat,
col="blue",
radius=3,
stroke=FALSE,
fillOpacity = 0.7,
#options = markerOptions(minZoom=15, maxZoom=20), # Oldcode
group = "Quake Points") %>% # Newcode
addPolygons(data= oceania,
col="red") %>%
groupOptions("Quake Points", zoomLevels = 15:20) # Newcode
来源:https://stackoverflow.com/questions/61503281/display-layers-at-certain-zoom-levels-in-r-leaflet