leaflet.extras: measure distance in metres - r

I would like to create a map where I can interactively measure the distance between 2 points. Luckily, leaflet.extras has exactly what I need, however, I'm struggling to get it to produce the outputs in metres (or kilometres) as opposed to feet.
Consider the below piece of code:
library(leaflet)
library(leaflet.extras)
leaflet() %>%
addTiles() %>%
addDrawToolbar(
editOptions=editToolbarOptions(selectedPathOptions=selectedPathOptions())
)
It creates the following map:
However, this example (chunk 3) effectively the same code to create the same measuring tool (polyline), except it works in KM, whereas my example works in feet.
If you have any tips that can help me switch to metres as opposed to feet, I would really appreciate it.

The drawPolylineOptions function does not allow to set the option feet=FALSE.
Hence, I suggest to modify drawPolylineOptions as follows:
library(leaflet)
library(leaflet.extras)
mydrawPolylineOptions <- function (allowIntersection = TRUE,
drawError = list(color = "#b00b00", timeout = 2500),
guidelineDistance = 20, metric = TRUE, feet = FALSE, zIndexOffset = 2000,
shapeOptions = drawShapeOptions(fill = FALSE), repeatMode = FALSE) {
leaflet::filterNULL(list(allowIntersection = allowIntersection,
drawError = drawError, guidelineDistance = guidelineDistance,
metric = metric, feet = feet, zIndexOffset = zIndexOffset,
shapeOptions = shapeOptions, repeatMode = repeatMode)) }
leaflet() %>% setView(10.975342,45.421588,9) %>%
addTiles() %>%
addProviderTiles(providers$OpenStreetMap.Mapnik) %>%
addDrawToolbar(
polylineOptions = mydrawPolylineOptions(metric=TRUE, feet=FALSE),
editOptions=editToolbarOptions(selectedPathOptions=selectedPathOptions())
)
Otherwise, using addMeasures you can add to your map a useful tool to measure distances (see the icon at the top right corner of the map).
It is possibile to specify units used to display length results by the primaryLengthUnit option.
leaflet() %>% setView(10.975342,45.421588,9) %>%
addTiles() %>%
addProviderTiles(providers$CartoDB.Positron) %>%
addDrawToolbar(
editOptions=editToolbarOptions(selectedPathOptions=selectedPathOptions())
) %>%
addMeasure(primaryLengthUnit="kilometers", secondaryLengthUnit="kilometers")

Related

Leaflet map with R shows country completely grey

I am starting to become familiar with leaflet in R although I am experiencing some issues. Data works properly when I am plotting the map with ggplot2. However, I was asked to switch to a more dynamic and interactive map for a shiny dashboard. Here I report the code I performed with the image of the 'grey' results I obtained. I am plotting some Italian provincial data. I retrieved the shape file from the website of the Italian Institute of Statistics (2020, versione generalizzata). Nonetheless, I have uploaded the dataframe and the shape file also on GitHub.
library(dplyr)
library(leaflet)
library(rgdal)
library(sf)
# Import data
load('C:/[...]/data_19.rda') # <--- There are several variables, I selected just one of them
# Import Italy shapefile
ita_map = readOGR('C:/[...]/Limiti01012020_g/ProvCM01012020_g',
'ProvCM01012020_g_WGS84', stringsAsFactors = FALSE)
# Merge
colnames(data_19)[1] = "COD_PROV" # <--- This is the numerical provincial code
ita_map_sf = st_as_sf(ita_map)
ita_map_data <- left_join(ita_map_sf, data_19, by = "COD_PROV")
# Generate map with leaflet
ita_map_data %>%
st_transform(crs = 4326) %>%
leaflet() %>%
addProviderTiles("Esri.WorldGrayCanvas") %>%
setView(lat = 41.8719, lng = 12.5674, zoom = 5) %>%
addPolygons(
fillColor = ita_map_data$unilav_ula,
stroke = FALSE,
smoothFactor = 0.2,
fillOpacity = 0.3
)
Here, instead, the result I am getting from the viewer:
I guess there are some problems in the way I dealt with the polygon data frame. I hope someone could give me some hints. Thank you in advance.
See the R leaflet documentation page for plotting Choropleth Maps:
https://rstudio.github.io/leaflet/choropleths.html
You need to specify a color palette you want to use for the map.
The following code produces the output below.
library(dplyr)
library(leaflet)
library(rgdal)
library(sf)
# Import data
load('C:/[...]/data_19.rda') # <--- There are several variables, I selected just one of them
# Import Italy shapefile
ita_map = readOGR('C:/[...]/Limiti01012020_g/ProvCM01012020_g',
'ProvCM01012020_g_WGS84', stringsAsFactors = FALSE)
# Merge
colnames(data_19)[1] = "COD_PROV" # <--- This is the numerical provincial code
ita_map_sf = st_as_sf(ita_map)
ita_map_sf$COD_PROV <- as.numeric(ita_map_sf$COD_PROV)
ita_map_data <- left_join(ita_map_sf, data_19, by = "COD_PROV")
# Specify Color Palette
pal <- colorQuantile("Blues", domain = ita_map_data$unilav_ula, n=5)
# Generate map with leaflet
ita_map_data %>%
st_transform(crs = 4326) %>%
leaflet() %>%
addProviderTiles("Esri.WorldGrayCanvas") %>%
setView(lat = 41.8719, lng = 12.5674, zoom = 5) %>%
addPolygons(
fillColor = ~pal(unilav_ula),
stroke = FALSE,
smoothFactor = 0.2,
fillOpacity = 0.7,
label=~unilav_ula
)

Create leaflet map with mainland country and overseas territories grouped together

I was wondering whether it would possible to easily group mainland France with its overseas territories on a leaflet map, similarly to what we often see for the USA.
Something like the map below.
Ideally, I could still use regular coordinates to place points on the map, but that may not be possible. I've spent a few hours to try and figure it out, but lamentably failed...
I guess one solution would be to modify the original shapefile to move the polygons of interest and expand them proportionally, but that would not be very straightforward (note that that kind of shapefile may already exist, but if it does, I haven't used the right keywords)
Any idea?
Thanks for your help :)
Using the first link provided by #Will Hore Lacy Multiple leaflets in a grid, you can use htmltools to create the desired view.
library(htmltool)
library(leaflet)
First, create all maps, providing different heights for each map.
# main map
# indicate height (should be related to the number of other maps : 800px = 4 maps * 200px)
metropole <- leaflet(height = "800px") %>%
addTiles() %>%
setView(lng = 2.966, lat = 46.86, zoom = 6) %>%
addControl("Métropole", position = "bottomleft")
# smaller maps :
# height is identical (200px)
reunion <- leaflet(height = "200px") %>%
addTiles() %>%
setView(lng = 55.53251, lat = -21.133165, zoom = 8) %>%
addControl("La Réunion", position = "bottomleft")
martinique <- leaflet(height = "200px") %>%
addTiles() %>%
setView(lng = -61.01893, lat = 14.654532, zoom = 8) %>%
addControl("Martinique", position = "bottomleft")
guadeloupe <- leaflet(height = "200px") %>%
addTiles() %>%
setView(lng = -61.53982, lat = 16.197587, zoom = 8) %>%
addControl("Guadeloupe", position = "bottomleft")
guyane <- leaflet(height = "200px") %>%
addTiles() %>%
setView(lng = -53.23917, lat = 3.922325, zoom = 6) %>%
addControl("Guyane", position = "bottomleft")
Create the HTML grid.
leaflet_grid <-
tagList(tags$table(width = "100%", border = "1px",
tags$tr(
tags$td(reunion, width = "30%"), # reduce first column width
tags$td(metropole, rowspan = 4) # span across the four other maps
),
tags$tr(
tags$td(martinique)
),
tags$tr(
tags$td(guadeloupe)
),
tags$tr(
tags$td(guyane)
)
)
)
browsable(leaflet_grid)
This should give something like this :

Display David Rumsey' Georeferencer tiles in R leaflet

I am trying tu use David Rumsey' Georeferencer tiles in R leaflet package without success (Only the OSM basemap is displayed).
According to the package vignette I tried :
library(leaflet)
# XYZ direct link
leaflet() %>%
setView(0.65, 0, zoom = 5) %>%
addTiles() %>%
addTiles("https://maps.georeferencer.com/georeferences/700526190853/2017-12-30T11:48:27.589686Z/map.json?key=D7AwmpRP1H6pUic6DIK3")
and
library(leaflet)
# WMS tiles
leaflet() %>%
addTiles() %>% setView(0.65, 0, zoom = 5) %>%
addWMSTiles(
"https://maps.georeferencer.com/georeferences/700526190853/2017-12-30T11:48:27.589686Z/wmts?key=D7AwmpRP1H6pUic6DIK3&SERVICE=WMTS&REQUEST=GetCapabilities",
layers = "1", # I assume
options = WMSTileOptions(format = "image/png", transparent = FALSE),
attribution = "")
Notes :
- The access at the map links need free registration.
- I used the 2.1 package release.
- The vignette's addWMSTiles example is working on my computer.
I solve my problem using the addLayersControl function that can allow me to choose the layer to display.
library(leaflet)
m <- leaflet() %>%
addProviderTiles(providers$CartoDB.DarkMatterNoLabels, group = "DarkMatter") %>%
addTiles("https://maps.georeferencer.com/georeferences/700526190853/2017-12-30T11:48:27.589686Z/map/{z}/{x}/{y}.png?key=D7AwmpRP1H6pUic6DIK3", group ="H") %>%
addLayersControl(
baseGroups = c("DarkMatter", "H"), position ="topleft")
m

How to "addTiles" on top of "addPolygons" in R's Leaflet?

How do you set the layer order in R's leaflet package so that tiles show up on top of polygons filled with color?
Here's what I've got so far:
require(leaflet)
require(acs)
require(tigris)
require(rgdal)
census.income.end.year = 2015
county = 17
nd.counties=acs.fetch(geography=geo.make(state="ND", county=county),
table.number="B01003", endyear = 2015)
tracts <- tigris::tracts(state = 'ND', county = county, cb=FALSE, year = 2015)
# create a geographic set to grab tabular data (acs)
geo<-geo.make(state=c("ND"),
county = county,
tract="*")
# add in median income
median.income <- acs.fetch(endyear = census.income.end.year,
geography = geo,
variable = c("B19013_001"))
income_df <- data.frame(paste0(as.character(median.income#geography$state),
str_pad(as.character(median.income#geography$county), 3, 'left', '0'),
str_pad(as.character(median.income#geography$tract), 5, 'left', '0')),
median.income#estimate)
rownames(income_df)<-1:nrow(income_df)
names(income_df)<-c("GEOID", "hhincome")
income_merged <- geo_join(tracts, income_df, "GEOID", "GEOID")
income_merged <- spTransform(income_merged, CRS("+init=epsg:4326"))
qpal <- colorQuantile("plasma", income_df$hhincome, n = 4)
leaflet() %>%
setView( -96.7898, 46.8772, zoom=11) %>%
addPolygons(data = income_merged,
fillColor = qpal(income_merged$hhincome),
fillOpacity = 1,
weight = 0.3) %>%
addProviderTiles(providers$Hydda.RoadsAndLabels)
Ultimately, I'ld like to do this with addTiles (instead of addProviderTiles as in the above code) using a custom MapBox, but I can't figure out how to make that reproducible for this example... given that you need a key to access custom MapBox tiles (BTW, I've created a custom MapBox tile that should be transparent except for roads and labels, so the underlying polygons should "show thru.")
Here is one way to do add a tile on top of a circle with the non-R version of leaflet: http://jsfiddle.net/dcu9pz2w/, but I don't see how to make that work in my context. I think adding "panes" may be the way to go, but I don't see that functionality in R leaflet. Also, I explored z-index values, but that seemed to be a dead end.
Any help is much appreciated!
R leaflet now includes addMapPane function. The solution to this problem is to first set up pane order and then add tiles/polygons. Reproducible example:
library(leaflet)
library(geojsonio)
# get polygon data
# https://github.com/simonepri/geo-maps/blob/master/info/countries-land.md
world <- geojson_read(
"https://github.com/simonepri/geo-maps/releases/download/v0.6.0/countries-land-10km.geo.json",
what = "sp"
)
# generate random values
world#data$value <- runif(nrow(world#data))
# get color palette
color_pal <- colorNumeric(palette = "YlOrRd", domain = NULL)
# get leaflet map
leaflet() %>%
setView(lat = 50, lng = 15, zoom = 4) %>%
addMapPane("background_map", zIndex = 410) %>% # Level 1: bottom
addMapPane("polygons", zIndex = 420) %>% # Level 2: middle
addMapPane("labels", zIndex = 430) %>% # Level 3: top
addProviderTiles(
providers$Esri.WorldTerrain,
options = pathOptions(pane = "background_map")
) %>%
addPolygons(
data = world, stroke = FALSE, smoothFactor = 0.2,
fillOpacity = 0.6, fillColor = ~color_pal(value),
options = pathOptions(pane = "polygons")
) %>%
addProviderTiles(
providers$Stamen.TonerLabels,
options = pathOptions(pane = "labels")
)

Cross-group clustering and overlay group control with leaflet in R?

I am trying to accomplish the equivalent of Ghybs Leaflet example found here, where selecting/deselecting an overlay group shows/hides the markers for a group and updates the clustering accordingly using R's leaflet package.
There is a partial solution with R here:
quakes <- quakes %>%
dplyr::mutate(mag.level = cut(mag,c(3,4,5,6),
labels = c('>3 & <=4', '>4 & <=5', '>5 & <=6')))
quakes.df <- split(quakes, quakes$mag.level)
l <- leaflet() %>% addTiles()
names(quakes.df) %>%
purrr::walk( function(df) {
l <<- l %>%
addMarkers(data=quakes.df[[df]],
lng=~long, lat=~lat,
label=~as.character(mag),
popup=~as.character(mag),
group = df,
clusterOptions = markerClusterOptions(removeOutsideVisibleBounds = F),
labelOptions = labelOptions(noHide = F,
direction = 'auto'))
})
l %>%
addLayersControl(
overlayGroups = names(quakes.df),
options = layersControlOptions(collapsed = FALSE)
)
This solution does not cluster markers across groups, even though they are proximate points. A heads up for anyone trying to recreate this solution: you need to remove label=~as.character(mag), and labelOptions = labelOptions(noHide = F, direction = 'auto') in order for the code to run.
How can I accomplish cross-group clustering while maintaining layer control ?

Resources