I have recently discovered the r package “leaflet” and found a great blog with some basic instruction for creating an interactive map (found here) http://mhermans.net/hiking-gpx-r-leaflet.html.
I have not, however been successful at adding a scale bar on the map. That is, I’d like to add a graphic feature that scales distance as you zoom in and out of the map (e.g. a bar at the bottom of the map that represents 1km). The leaflet site (found here) http://leafletjs.com/reference.html#control-scale-l.control.scale discusses this feature: L.control,scale().
Does anyone know how to add a scale bar??
This is the code for my map so far (The “Add Scale Bar” Does NOT work):
# A map of Track data
Mymap <- leaflet() %>% addTiles() %>%
addPolylines(data=Dofu1) %>%
addPolylines(data=Zak1) %>%
addProviderTiles("Esri.WorldImagery")
# Add a legend
Mymap %>%
addLegend(position = 'topright',
colors = "blue",
labels = 'Buruku Tracks', opacity = 0.5,
title = '')
# Add a Scale Bar
Mymap %>%
addControl(Mymap, "Scale",
position = c("topright"),
layerID = NULL,
className = "Scale",
data - getMapData(Mymap))
This feature has been added to the development version of the leaflet package. See Add support for scale bar. Also, the second argument to addControl expects html as either a character string or html generated from Shiny or htmltools tags. Finally, I think you have a typo in addControl: data - getMapData(Mymap) should be data = getMapData(Mymap)
the scale bar function is implemented and can be added with 'addScaleBar'
leaflet() %>%
addTiles() %>%
addScaleBar()
Related
I have a leaflet map, which has points that overlap when zoomed out. I have therefore used markerClusterOtions() so that as the user zooms in, the overlapping points that were grouped into clusters will separate.
This is all working fine, but my problem is that I would like to apply a zoom limit. I don't want the users to be able to zoom right in to street level, because then they could see the exact address of my markers (which in this case would be a data protection issue). I want the markers to freeze when the user reaches the max zoom limit, but until then, they should keep separating out as the user zooms in.
I thought this could be achieved by setting the maxZoom in tileOptions, and freezeAtZoom in markerClusterOptions, but it doesn't work and I keep getting a strange error.
Here is my code:
# Create the interactive map:
myleaflet <- leaflet() %>%
# Add open street map (default base layer)
addTiles(tileOptions(minZoom = 1, maxZoom = 12)) %>%
# Add transformed shapefile of regions
addPolygons(data = regions, weight = 5, col = "black") %>%
# Add markers for case residence with descriptive labels:
addMarkers(lng = mydata$home_long,
lat = mydata$home_lat,
popup = paste("ID: ", mydata$id, "<br/>",
"Link: ", mydata$links, "<br/>",
"Clade: ", mydata$wgs_cluster),
clusterOptions = markerClusterOptions(freezeAtZoom = "max"))
# View the map:
myleaflet
And here is the error I get (it appears when I try to view the map, not when running the code to create it):
Error in dirname(to) : path too long
If I remove the zoom options, I can view the map, but then the zoom is not limited.
I have looked at posts regarding this error, and I can see that it is associated with Windows OS and paths that are too long. I am using windows, and this is part of an R markdown chunk, but the chunk name is 24 characters (so within the limit) and the R markdown file name is short - also, the error only occurs when I run the above code, which is just part of the code in that chunk. I can't see how adding the zoom options makes something too long, since they are supposed to be valid arguments?
Any insights as to what I'm doing wrong would be much appreciated.
Update:
It seems my mistake was not specifying the argument name for tileOptions - also freezeAtZoom is not necessary to specify when the maximum zoom limit is already specified for the map tiles (in fact if both are specified, the unclustered markers also show up on the map).
The code below works:
# Create the interactive map:
myleaflet <- leaflet() %>%
# Add open street map (default base layer)
addTiles(options = tileOptions(maxZoom = 12)) %>%
# Add transformed shapefile of regions
addPolygons(data = regions, weight = 5, col = "black") %>%
# Add markers for case residence with descriptive labels:
addMarkers(lng = mydata$home_long,
lat = mydata$home_lat,
popup = paste("ID: ", mydata$id, "<br/>",
"Link: ", mydata$links, "<br/>",
"Clade: ", mydata$wgs_cluster),
clusterOptions = markerClusterOptions())
# View the map:
myleaflet
Since the first option in addTiles() is map I suppose that it was previously interpreting the tileOptions argument as a file path to a map, but I would be interested to know if there are other interpretations, since the traceback showed the problem with the file path length was in saving to html, not importing / reading a file.
Is there a way to make popup graphs appear on hover (rather than click) in Mapview? Alternatively, is it possible for the graphs to appear open by default? Rather than produce my own reproducible example, I would defer to the example given with the R Mapview documentation.
I am fairly new to R and Mapview so any guidance is greatly appreciated!
I've just pushed an update to package leafpop which provides the popup functionality used in mapview. This should provide what you want (at least partly - as mapview() will still need to be updated). This allows you to now specify tooltip = TRUE in addPopupImages (in addPopupGraphs via ...). Note that it is encouraged to use addPopup* functions over the classic popup* functions because they also work in non-interactive setting, e.g. when saving a map locally.
library(sf)
library(leaflet)
library(lattice)
library(leafpop)
pt = data.frame(x = 174.764474, y = -36.877245)
pt = st_as_sf(pt, coords = c("x", "y"), crs = 4326)
p2 = levelplot(t(volcano), col.regions = terrain.colors(100))
leaflet() %>%
addTiles() %>%
addCircleMarkers(data = pt, group = "pt") %>%
addPopupGraphs(
list(p2)
, group = "pt"
, width = 300
, height = 400
, tooltip = TRUE
)
Not sure when and how to integrate this into mapview() as this is a bit more complicated than the classic popup* functions (because we need to know something about the map object we create with mapview before we create it...). In any case, I hope this is at least partly useful and helps resolve your issue.
There is a similar question for R shiny here:Control the size of popupImage from leaflet in r shiny
But I am using flexdashboard. I have no background in CSS. How can I adjust the size? Sample code below:
library(leaflet)
library(mapview)
leaflet() %>%
addProviderTiles(providers$Esri.WorldStreetMap) %>%
addRectangles(
lng1 = bbox_north2$p1$long, lat1 = bbox_north2$p1$lat,
lng2 = bbox_north2$p2$long, lat2 = bbox_north2$p2$lat,
fillColor = "red", stroke = FALSE,
popup = popupImage(here::here("products", "north1.png"), width = 800, height = 600, embed = TRUE)
When setting width = 800, the popup displays larger, but a portion of it is greyed out.
Disclaimer: mapview developer here.
First of all, please note that the popup*() functions from mapview have been moved to a more light-weight package called leafpop. Though on CRAN, for this problem we need the development version from github which can be found here. - Uncomment the remotes::install_githib() call in the example below to get the latest version.
There have been numerous issues with the mapview popup functions that have lead me to rewrite most of them (including popupImage()). The rewriting introduces a new API design which is necessary as we need to have access to the map object. So for your issue at hand, the following should remedy your problem:
# remotes::install_github("r-spatial/leafpop")
library(leaflet)
library(leafpop)
img = "/path/to/some/image.png"
# does not work properly - image is clipped in y
leaflet() %>%
addTiles() %>%
addPolygons(data = franconia[1, ], popup = popupImage(img, width = 400))
# works
leaflet() %>%
addTiles() %>%
addPolygons(data = franconia[1, ], group = "fran") %>%
addPopupImages(image = img, group = "fran", width = 400)
Basically, you first create the (data) layer with the respective leaflet::add*() function (in the example case above addPolygons()) and then register the images as popups using addPopupImges() identifying the layer with the group argument. This should enable you to set whatever width and height you want (though I think the maxwidth value is 2000 pixels).
I want to make a Shiny app where the colouring of a choropleth is based on a numeric value of one of many possible quantitative variables that a user can select from. In simple cases, this is straightforward, but I'm unsure of the best practices when we have 20+ variables, with quite detailed shape files (~2300 polygons).
It might or might not be relevant that the variables might be completely independent to each other such as 'Total Population' or 'Average Temperature' but some of them will have a temporal relationship such as 'Total Population' at 3 or more points in time.
One of the main shapefiles I am using is the ABS Statistical Area 2. Below I give the population density (total population/area) for Australia and a zoomed in view of Sydney to better convey the level of detail I'm interested in.
Australia
Sydney
I have read the shapefile in to R and greatly reduced the complexity/number of points using the ms_simplify() function in the rmapshaper package.
Now as far as Shiny and leaflet go, this is what I have been doing:
Before the server object is defined in server.R, I build a primary map object with all the desired 'layers'. That is, a leaflet with numerous addPolygon() calls to define the colouring of each 'layer' (group).
# Create main map
primary_map <- leaflet() %>%
addProviderTiles(
providers$OpenStreetMap.BlackAndWhite,
options = providerTileOptions(opacity = 0.60)
) %>%
# Layer 0 (blank)
addPolygons(
data = aus_sa2_areas,
group = "blank"
) %>%
# Layer 1
addPolygons(
data = aus_sa2_areas,
fillColor = ~palette_layer_1(aus_sa2_areas$var_1),
smoothFactor = 0.5,
group = "layer_1"
) %>%
...
# Layer N
addPolygons(
data = aus_sa2_areas,
fillColor = ~palette_layer_n(aus_sa2_areas$var_n),
smoothFactor = 0.5,
group = "layer_n"
) %>% ...
All bar the first layer is then hidden using hideGroup() so that the initial rendering of the map doesn't look silly.
hideGroup("layer_1") %>%
hideGroup("layer_2") %>%
...
hideGroup("layer_n")
In the Shiny app, using radio buttons (layer_selection), the user can select the 'layer' they'd like to see. I use observeEvent(input$layer_selection, {}) to watch the status of the radio button options.
To update the plot, I use leafletProxy() and hideGroup() to hide all the groups and then showGroup() to unhide the selected layer.
I apologize for the lack of reproducible example.
Questions
How can I optimise my code? I am eager to make it more performant and/or easy to work with. I've found using hideGroup()'s/showGroup() for each layer selection is far faster than using addPolygon() to a blank map, but this causes the app to take a very significant amount of time to load.
Can I change the variable I am colouring the polygons by, without redrawing or adding those polygons again? To clarify, if I have 2 different variables to plot, both using the same shape data, do I have to do 2 distinct addPolygon() calls?
Is there a more automatic way to sensibly colour the polygons for each layer according to a desired palette (from the viridis package?). Right now I'm finding defining a new palette for each variable, rather cumbersome, eg:
palette_layer_n <- colorNumeric(
palette = "viridis",
domain = aus_sa2_areas$aus_sa2_areas$var_n
)
Side Question
How does this map on the ABS website work? It can be incredibly detailed and yet extremely responsive. Compare the Mesh Block detail to the SA2 (2310 polygons), example below:
Since you haven't gotten any answers yet, I'll post a few things that can maybe help you, based on a simple example.
It would of course be easier if yours was reproducible; and I suppose from looking around you have already seen that there are several related issues / requests (about re-coloring polygons), whereas it doesn't seem that a real solution has made it into any release (of leaflet) yet.
With the below work-around you should be able to avoid multiple addPolygons and can cover an arbitrary number of variables (for now I have just hard-coded a single variable into the modFillCol call though).
library(leaflet)
library(maps)
library(viridis)
mapStates = map("state", fill = TRUE, plot = FALSE)
# regarding Question 3 - the way you set the domain it looks equivalent
# to just not setting it up front, i.e. domain = NULL
myPalette <- colorNumeric(
palette = "viridis",
domain = NULL
)
mp <- leaflet(data = mapStates) %>%
addTiles() %>%
addPolygons(fillColor = topo.colors(10, alpha = NULL), stroke = FALSE)
# utility function to change fill color
modFillCol <- function(x, var_x) {
cls <- lapply(x$x$calls, function(cl) {
if (cl$method == "addPolygons") {
cl$args[[4]]$fillColor <- myPalette(var_x)
}
cl
})
x$x$calls <- cls
x
}
# modify fill color depending on the variable, in this simple example
# I just use the number of characters of the state-names
mp %>%
modFillCol(nchar(mapStates$names))
I'm trying to get de precipation radar data from the KNMI loaded in a leaflet in R. The data is located here: http://adaguc.knmi.nl/contents/webservices/WebServices_RADNL_OPER_R___25PCPRR_L3.html
So far, I've managed to get the current radar image to a leaflet layer with the following code:
require("leaflet")
require("dplyr")
leaflet() %>% addTiles() %>%
addWMSTiles(
"http://geoservices.knmi.nl/cgi-bin/RADNL_OPER_R___25PCPRR_L3.cgi",
layers = "RADNL_OPER_R___25PCPRR_L3_KNMI",
options = WMSTileOptions(format = "image/png", transparent = TRUE),
attribution = "KNMI"
)
So far so good...
But what I really would like, is to get a radar image from a given timestamp. The series goes back to 2009 (see example from the KNMI viewer here: http://geoservices.knmi.nl/viewer2.0/?srs=EPSG%3A3857&bbox=-725.7203842048766,6500000,1220725.7203842048,7200000&service=http%3A%2F%2Fgeoservices.knmi.nl%2Fcgi-bin%2FRADNL_OPER_R___25PCPRR_L3.cgi%3F&layer=RADNL_OPER_R___25PCPRR_L3_COLOR%24image%2Fpng%24true%24default%241%240&selected=0&dims=time$current&baselayers=streetmap$world_line ).
On the web, I have found several examples of leaflet that supports dates/times, (like this: http://apps.socib.es/Leaflet.TimeDimension/examples/example14.html), but unfortunalety I lack the skills to convert this example to the R-version of leaflet.
Can this be done? Can I, for example, retrieve the precipation radar image from 2017-01-07T04:00? If yes: where would/could I start?
Or if it cannot be done with leaflet; any other suggestions?
That was easier than expected ;-)
I just had to add a TIME-variable in the WMSTileOptions.
This works:
require("leaflet")
require("dplyr")
leaflet() %>% addTiles() %>%
addWMSTiles(
"http://geoservices.knmi.nl/cgi-bin/RADNL_OPER_R___25PCPRR_L3.cgi",
layers = "RADNL_OPER_R___25PCPRR_L3_COLOR",
options = WMSTileOptions(format = "image/png", transparent = TRUE, TIME = "2017-01-07T04:00:00"),
attribution = "KNMI neerslagradar"
)