Create smallest grid in leaflet R - r

I want to create the smallest grid as possible in leaflet R. How should I go about it ?
My current code is :-
leaflet()%>%
addTiles() %>%
setView(lng = 101.9758, lat = 4.21053, zoom = 10)) %>%
addGraticule(interval = 0.02, sphere = FALSE) %>%
addMarkers(101.6995, 3.1473)
Here the picture output from the code before zoom
Here the picture after zoom in
The grid quite large after I zoom in but if I change addGraticule(interval = 0.01), my laptop hang and no output result. I want the grid to be small as picture below
Is there other way I can achieve my aim?
I found other function that might help which is
addSimpleGraticule(
map,
interval = 20,
showOriginLabel = TRUE,
redraw = "move",
hidden = FALSE,
zoomIntervals = list(),
layerId = NULL,
group = NULL
)
zoomIntervals :- use different intervals in different zoom levels. If not specified, all zoom levels use value in interval option.
But I'm not sure how to specify zoomIntervals arguments.

The Documentation of the R function addSimpleGraticule is not very verbose, but you can get a hint about the required data structure here.
You can set the number of grid lines per meter depending on the zoom level indeed using the zoomIntervals option:
library(leaflet)
leaflet() %>%
addTiles() %>%
setView(lng = 101.6995, lat = 3.1473, zoom = 20) %>%
addMarkers(101.6995, 3.1473) %>%
addSimpleGraticule(
showOriginLabel = TRUE,
redraw = "move",
hidden = FALSE,
zoomIntervals = list(
list(start = 1, end = 3, interval = 10),
list(start = 4, end = 9, interval = 1),
list(start = 10, end = 17, interval = 0.1),
list(start = 18, end = 20, interval = 0.0002)
),
layerId = NULL,
group = NULL
)

Related

Converting Values using numberFormat in leaflegend on Shiny

I am building a Shiny app and am trying to get a resized leaflet legend using leaflegend. My dataset has several different measures in it, some that are raw counts and some percentages. I am trying to code the legend numberFormat so that it displays the appropriate format for each. I currently have the values in dat2$value and the properly formatted label in dat2$lbl. I have tried defining a function to execute this translation for numberFormat but am getting strange results.
#define getLabel
getLabel = function(x){
dat2$lbl[dat2$value == x]
}
#draw map on screen
leafletProxy("map") %>%
clearShapes() %>%
clearControls() %>%
addMapPane("polygons", zIndex = 410) %>%
addMapPane("borders", zIndex = 420) %>%
addPolygons(
data = dat2,
stroke = T,
color = "#343434",
weight = 0.5,
opacity = 1,
fillColor = ~ pal(dat2$value),
fillOpacity = 0.8,
smoothFactor = 0.2,
popup = content,
options = pathOptions(pane = "polygons")
) %>%
addLegendBin(
pal = pal,
values = dat2$value,
numberFormat = function(x) lapply(x, getLabel),
title = input$group,
position = "topleft",
orientation = "vertical"
)
Resulting output:
Any thoughts on what is going wrong here? I feel so close, but can't quite get it to where I need it to be.

Leaflet layer control not toggling or displaying correct data from input

I am trying to add layers to a leaflet map in which they layers can toggle the circle markers by ranges (0 - 100, 100 - 200, etc) but for some reason when I toggle the 100 - 200ft layer nothing changes on the map. The 'All' and 'AMA' layers will toggle.
Moreover the 100-200 layer is not displaying the data that is within the b dataframe. The b dataframe only contains values from 100 - 200 in the dtw column but the markers on the map are displaying below 100 and above 200 values.
However the x dataframe will display the entire dataframe from 0 -1000 and will toggle correctly.
All of the sf objects are in the same CRS and are of the same class.
I am new to leaflet and layer controls and I would really appreciate some help. Here are images of the leaflet map not toggling correctly. Thanks!
x = usgs_spatial %>% st_transform(4326)
ama3 = ama %>% st_transform(4326)
pal1 = RColorBrewer::brewer.pal(9,"Blues")
pal2 = RColorBrewer::brewer.pal(9,"YlOrRd")
pals1 = colorNumeric(pal1, domain = x$dtw)
pals2 = colorNumeric(pal2, domain = x$dtw)
pals3 = colorBin("magma", domain = 1:8)
a = dtw_range(x, 0, 100) %>% select(wellid, date, dtw, measurement_dist)
b = dtw_range(x, 100, 200) %>% select(wellid, date, dtw, measurement_dist)
c = dtw_range(x, 200, 300) %>% select(wellid, date, dtw, measurement_dist)
leaflet() %>%
addProviderTiles(providers$CartoDB.Positron,[enter image description here][1] group = 'Tiles') %>%
addCircleMarkers(data = b, #clusterOptions = markerClusterOptions(interactive()),
color = ~pals2(dtw), fillOpacity = .5,
stroke = FALSE,
popup = leafpop::popupTable(st_drop_geometry(x[,c(4, 7, 8, 13)]),
feature.id = FALSE,
row.numbers = FALSE), group = '100 - 200 ft') %>%
addCircleMarkers(data = x, #clusterOptions = markerClusterOptions(interactive()),
color = ~pals2(dtw), fillOpacity = .5,
stroke = FALSE,
popup = leafpop::popupTable(st_drop_geometry(x[,c(4, 7, 8, 13)]),
feature.id = FALSE,
row.numbers = FALSE), group = 'All') %>%
addPolygons(data = ama3,
fillColor = ~pals3(OBJECTID),
color = 'black',
label = ~MAP_LABEL, group = 'AMA') %>%
addLayersControl(overlayGroups = c('All', '100-200 ft', 'AMA'), baseGroups = c("Tiles"))
I figured it out, I had not changed the x argument in the popupTable() to the appropriate dataframe, and I also had spaces between the '-' in the addlayGroup() for '100-200 ft' which is why the toggle option was not being picked up.

How to download geojson data and read it to R

# From http://leafletjs.com/examples/choropleth/us-states.js
states <- geojsonio::geojson_read("json/us-states.geojson", what = "sp")
bins <- c(0, 10, 20, 50, 100, 200, 500, 1000, Inf)
pal <- colorBin("YlOrRd", domain = states$density, bins = bins)
labels <- sprintf(
"<strong>%s</strong><br/>%g people / mi<sup>2</sup>",
states$name, states$density
) %>% lapply(htmltools::HTML)
leaflet(states) %>%
setView(-96, 37.8, 4) %>%
addProviderTiles("MapBox", options = providerTileOptions(
id = "mapbox.light",
accessToken = Sys.getenv('MAPBOX_ACCESS_TOKEN'))) %>%
addPolygons(
fillColor = ~pal(density),
weight = 2,
opacity = 1,
color = "white",
dashArray = "3",
fillOpacity = 0.7,
highlight = highlightOptions(
weight = 5,
color = "#666",
dashArray = "",
fillOpacity = 0.7,
bringToFront = TRUE),
label = labels,
labelOptions = labelOptions(
style = list("font-weight" = "normal", padding = "3px 8px"),
textsize = "15px",
direction = "auto")) %>%
addLegend(pal = pal, values = ~density, opacity = 0.7, title = NULL,
position = "bottomright")
The above code is copied from https://rstudio.github.io/leaflet/choropleths.html.
I am trying to reproduce the output. However, I got stuck in the first step - downloading the geojson file. I used the link shown in the first line, and save it as a text file and then rename it as a geojson file. But I failed to read that file. Obviously something wrong with file download or loading to R, but I have no idea where it is.
Can someone give any instructions? I have never deal with geojson data before. I just need help with the first two lines of codes, and I can handle all the others by myself.
The download file has a javascript assignment at the head. Removing it seems to fix the issue ,
library(geojson)
library(geojsonio)
url <- "http://leafletjs.com/examples/choropleth/us-states.js"
# read as text file
doc <- readLines(url)
# remove the javascript assignment at the front
doc2 <- gsub("var statesData = ", "", doc)
# write out as a temp file and read
write(doc2, file = "tempgeo.json")
states <- geojson_read("tempgeo.json", what = "sp")

leaflet - point on the map moves when zoom in and out

I used leaflet package to creates a map widget, and then added two layers with the function addMarkers(). However, I found that the points on the map change their positions when zoom in and out. The relative scripts are as following:
First, create a function pchIcons with r shapes in leaflet
pchIcons <- function(pch = 0:14, width = 30, height = 30, col = 1:15, ...) {
pchLength <- length(pch)
pchFiles <- character(pchLength)
# create a sequence of png images
for (i in seq_len(pchLength)) {
pchTempFile <- tempfile(fileext = '.png')
png(pchTempFile, width = width, height = height, bg = 'transparent')
par(mar = c(0, 0, 0, 0))
plot.new()
points(.5, .5, pch = pch[i], cex = 1.5, col = col[i], ...)
dev.off()
pchFiles[i] = pchTempFile
}
pchFiles
}
Then create a base layer with Paris' position, and add two layers, each layer represents one group.
baseLayer <- leaflet(zero) %>%
addProviderTiles("Stamen.Toner") %>%
setView(posParis[["lng"]], posParis[["lat"]], zoom = 12)
addZeroLayer <- baseLayer %>%
addMarkers(popup = paste(paste(zero$Code, zero$Ecart),
zero$Address,
sep = "<br/>"),
lng = as.numeric(zero$Long),
lat = as.numeric(zero$Lat),
icon = ~ icons(
iconUrl = pchIcons(rep(magasinEcart[1], nrow(zero)),
40,
40,
col = colorZero,
lwd = 2)
),
group = '0')
addOneLayer <- addZeroLayer %>%
addMarkers(popup = paste(paste(one$Code, one$Ecart),
one$Address,
sep = "<br/>"),
lng = as.numeric(one$Long),
lat = as.numeric(one$Lat),
icon = ~ icons(
iconUrl = pchIcons(rep(magasinEcart[2], nrow(one)),
40,
40,
col = colorOne,
lwd = 2)
),
group = '1')
Next, add UI controls to switch layers on and off with addLayersControl() and add legend with addLegend().
mapTourist <- addOneLayer %>%
addLayersControl(overlayGroups = c('0', '1'),
options = layersControlOptions(collapsed = FALSE)) %>%
addLegend("bottomright",
pal = colorFactor(brewer.pal(9, 'Set1')[3:4],
unique(magasinBaseComp$Ecart)),
values = names(magasinEcart),
title = "Ecart",
opacity = 1)
Finally, we can find that when zoom in or out, the points on map moves (as screenshots show).
Does someone know what's the problem and how could I solve it? Any idea is welcomed!

Leaflet map legend in R Shiny app has doesn't show colors

When I try to add a legend to a leaflet map for a leaflet map (using the Leaflet for R package) incorporated into a Shiny app, the legend does not show the colors of the color palette. Instead it only shows the colors specified for the NA values, in this case, white.
The app does the following:
First, it filters a set of data based on user inputs
Then it generates a choropleth map from the filtered data
This is the code I used to make the legend:
addLegend(position = "bottomleft",
pal = pal, values = shp.data()$stat.selected,
title = "Legend",
opacity = .5)
Where pal is a quantile color palette as follows
pal <-colorQuantile(c("#B2FF66","#66CC00","#4C9900","#336600","#193300"),
NULL, n = 5, na.color="#FFFFFF")
shp.data() is a reactive expression that is a shapefile filtered based on user inputs and stat_selected is the specific statistic that the user selects for mapping onto colors.
I get the following warnings:
Warning in is.na(x) :
is.na() applied to non-(list or vector) of type 'NULL'
Warning in is.na(values) :
is.na() applied to non-(list or vector) of type 'NULL'
I initially tried to make the legend following the example on the leaflet for R page and used the argument values = ~stat.selected for the addLegend function, but I got this error:
Error in UseMethod("doResolveFormula") :
no applicable method for 'doResolveFormula' applied to an object of class "NULL"
Earlier I had just a simple snippet that showed how to add legends. I did not use the ~ before the legend values as is the norm. I did the traditional dataframe$column and it works nicely.
This is now updated to see how it all fits together. Here is a full-fledged mapping run after creating all of the variable cuts, etc. The final cleansed data frame was called zipData
# create a full popup
# add some HTML for editing the styles
zipData$popUp <- paste('<strong>',zipData$Street, '</strong><br>',
'TIV = $',prettyNum(zipData$tiv, big.mark = ',',preserve.width = 'none'), '<br>',
'City: ', zipData$city, '<br>',
'YrBuilt = ', zipData$YearBuilt, '<br>',
'Construction = ', zipData$ConstructionCode, '<br>',
'Occupancy = ', zipData$OccupancyCode, '<br>',
'Premium = $' , prettyNum(zipData$Premium, big.mark = ',',preserve.width = 'none') , '<br>',
'GrossArea = ', prettyNum(zipData$GrossArea, big.mark = ',', preserve.width = 'none'), '<br>',
'RoofYr = ', zipData$RoofYearBuilt, '<br>')
# set color scale for key factor
colorsConst <- colorFactor(rainbow(4), zipData$ConstructionCode)
# color scales for numerical bins
colorstivValue <- colorFactor(palette = 'Accent', zipData$tivValueLvl)
colorsYrBuilt <- colorFactor(palette = 'Spectral', zipData$yrBuiltLvl)
colorsRoofYrBuilt <- colorFactor(palette = "YlOrRd", zipData$roofYrBuiltLvl)
# begin the leaflet map construction
# create the map opbject
m <- leaflet() %>%
addTiles() %>%
# add different tiles for different color schemes
addProviderTiles(providers$OpenStreetMap, group = 'Open SM') %>%
addProviderTiles(providers$Stamen.Toner, group = 'Toner') %>%
addProviderTiles(providers$CartoDB.Positron, group = 'CartoDB') %>%
addProviderTiles(providers$Esri.NatGeoWorldMap, group = 'NG World') %>%
setView(lng = -90, lat = 30, zoom = 10) %>%
##############################
# this section is for plotting the variables
# each variable below is a layer in the map
# construction
addCircleMarkers(data = zipData, lat = ~Lat, lng = ~Lon,
color = ~colorsConst(ConstructionCode), popup = zipData$popUp,
radius = 5, group = 'Construction') %>%
# tiv
addCircleMarkers(data = zipData, lat = ~Lat, lng = ~Lon,
color = ~colorstivValue(tivLvl), popup = zipData$popUp,
radius = ~tiv/20000, group = 'Bldg Value') %>%
# year built
addCircleMarkers(data = zipData, lat = ~Lat, lng = ~Lon,
color = ~colorsYrBuilt(yrBuiltLvl), popup = zipData$popUp,
radius = ~YearBuilt/250, group = 'Yr Built') %>%
######################################
# layer control
addLayersControl(
baseGroups = c('Open SM', 'Toner', 'Carto DB', 'NG World'),
overlayGroups = c('Construction',
'TIV',
'Yr Built'
),
options = layersControlOptions(collapsed = F)
) %>%
#################################################
add the legends for each of the variables
# construction
addLegend('bottomright', pal = colorsConst, values = zipData$ConstructionCode,
title = 'Construction Code',
opacity = 1) %>%
# tiv
addLegend('bottomleft', pal = colorstivValue, values = zipData$tivLvl,
title = 'TIV',
opacity = 1) %>%
# year built
addLegend('topleft', pal = colorsYrBuilt, values = zipData$yrBuiltLvl,
title = 'Yr Built',
opacity = 1)
m # Print the map
A portion of the map is shown below.
I was able to make the colors showing up by changing the way I was referencing the values column in the arguments of the AddLegend function. I put the stat.selected variable in double brackets, which seemed to fix the problem:
addLegend(position = "bottomleft",
pal = pal, values = shp.data()[[stat.selected]],
title = "Legend",
opacity = 1
)
For clarification, the stat.selected variable comes from the following switch statement:
stat.selected <- isolate(switch(input$var.stat,
"Total employment" = "tot_emp",
"Mean annual wage" = "a_mean",
"Mean hourly wage" = "h_mean",
"Location quotient" = "loc_quotient"
)
where "tot_emp", "a_mean", "h_mean", and "loc_quotient" are column names in the shp.data spatial polygons data frame.
I guess the problem was that I was trying to pass in the column name by variable using a $.
I'm still a fairly novice R user, so if anyone can explain why the example in the Leaflet for R documentation does not work in this case I would appreciate it.
I had the same message
Error in UseMethod("doResolveFormula") : no applicable method for 'doResolveFormula' applied to an object of class "NULL"
with
data <- data.frame(lng1 = c(1, 2, 3),
lng2 = c(2, 3, 4),
lat1 = c(1, 2, 3),
lat2 = c(2, 3, 4),
values = c(1, 2, 3))
pal_grid <- colorNumeric(palette = "YlGn", domain = data$values)
leaflet() %>%
addRectangles(lng1 = data$lng1, lat1 = data$lat1,
lng2 = data$lng2, lat2 = data$lat2,
fillColor = ~pal_grid(data$values),
fillOpacity = 0.2,
weight = 2, opacity = 0.5)
The solution is to provide to leaflet the data that you are using to create the element in the main call to leaflet() or in the call to any element that you add after that.
In the main call to leaflet():
data <- data.frame(lng1 = c(1, 2, 3),
lng2 = c(2, 3, 4),
lat1 = c(1, 2, 3),
lat2 = c(2, 3, 4),
values = c(1, 2, 3))
pal_grid <- colorNumeric(palette = "YlGn", domain = data$values)
leaflet(data = data) %>%
addRectangles(lng1 = data$lng1, lat1 = data$lat1,
lng2 = data$lng2, lat2 = data$lat2,
fillColor = ~pal_grid(data$values),
fillOpacity = 0.2,
weight = 2, opacity = 0.5)
At the moment of add elements:
data <- data.frame(lng1 = c(1, 2, 3),
lng2 = c(2, 3, 4),
lat1 = c(1, 2, 3),
lat2 = c(2, 3, 4),
values = c(1, 2, 3))
pal_grid <- colorNumeric(palette = "YlGn", domain = data$values)
leaflet() %>%
addRectangles(data = data,
lng1 = data$lng1, lat1 = data$lat1,
lng2 = data$lng2, lat2 = data$lat2,
fillColor = ~pal_grid(data$values),
fillOpacity = 0.2,
weight = 2, opacity = 0.5)`

Resources