Within addPolygons() there is a popup parameter just like the one in the addPopups() function. The difference (I think) is that when the popup is created within addPolygons(), one can click anywhere within the polygon to trigger the popup, but if addPopups() is used, a single lng and lat point must be defined.
I want to change one of the default options (maxWidth) in popupOptions() which can easily be done when using addPopups() because it contains the parameter options = popupOptions() but I don't know how to do it when using addPolygons(); within that function the options parameter is options = pathOptions().
Below is a reproducible example from the leaflet documentation with a popup added that I'd like increase the maxWidth.
library(rgdal)
# From https://www.census.gov/geo/maps-data/data/cbf/cbf_state.html
states <- readOGR("shp/cb_2013_us_state_20m.shp",
layer = "cb_2013_us_state_20m", verbose = FALSE)
neStates <- subset(states, states$STUSPS %in% c(
"CT","ME","MA","NH","RI","VT","NY","NJ","PA"
))
leaflet(neStates) %>%
addPolygons(
stroke = FALSE, fillOpacity = 0.5, smoothFactor = 0.5,
color = ~colorQuantile("YlOrRd", states$AWATER)(AWATER),
popup="<b>Hello World</b>"
)
You can do this simply by adding popupOptions() after your popup in the addPloygons() block like so:
leaflet(neStates) %>%
addPolygons(
stroke = FALSE, fillOpacity = 0.5, smoothFactor = 0.5,
color = ~colorQuantile("YlOrRd", states$AWATER)(AWATER),
popup="<b>Hello World</b>"
popupOptions = popupOptions(maxWidth ="100%", closeOnClick = TRUE)
)
Here is the list from the PDF vignette on leaflet R of all the things you can drop in the popupOptions() list:
popupOptions(maxWidth = 300, minWidth = 50, maxHeight = NULL,
autoPan = TRUE, keepInView = FALSE, closeButton = TRUE,
zoomAnimation = TRUE, closeOnClick = NULL, className = "", ...)
Related
i have somehow a quite tricky question. Im creating an interactive leaflet map in my shinydashboard. Everything works fine (the error just appears because its waiting for some text input to be processed and then mapped).
But.. I don't get the map to work, when only the first textinput is given some Input. One must insert something in the second, which is not handy and can lead to some weird results. If nothing is insert, the script doesn't get any further and is stuck.
Wrap up. How its possible to make the second textinput obligatory?
Is there a workaround or a possibility to deactivate the second textinput until one inserts a string? Otherwise the script just waits and waits (throws this error because no string is given which can be processed obviously)...
Structure
textinput from shiny dashboard -> parsed into google_places request -> tidy -> returns points (Lon, Lat) -> gets displayed on the leaflet map.
The Dashboard
Even though it must not have to do with the leaflet-map I provide a shrinked code. Its the second addCircleMarkers argument.
The map
map$dat <-leaflet () %>%
addProviderTiles(providers$CartoDB.Positron, group = "Positron Design") %>%
addMarkers(lat= Ort_geocode()$lat, lng= Ort_geocode()$lng, group = "Standort") %>%
addCircleMarkers(data = cowork(), popup = paste(as.character(cowork()$name), "</br>", cowork()$rating),fill =TRUE, fillColor ="#20205F", stroke =FALSE, fillOpacity = 0.8, group = "Erste Nutzung",
labelOptions = labelOptions(noHide = T, textOnly = TRUE, direction = "bottom", style = list("color" = "black", "font-size" = "11px", "font-family" = "AkkuratStd", "font-style" = "Thin"))) %>%
addCircleMarkers(data = Zweite_Nutzung(), popup = paste(as.character(Zweite_Nutzung()$name), "</br>", Zweite_Nutzung()$rating), fill =TRUE, fillColor ="#607758", stroke =FALSE, fillOpacity = 0.8, group = "Zweite Nutzung" ,
labelOptions = labelOptions(noHide = T, textOnly = TRUE, direction = "bottom", style = list("color" = "black", "font-size" = "11px", "font-family" = "AkkuratStd", "font-style" = "Thin"))) %>%
addHeatmap(data = cowork(), lng= cowork()$lng,lat= cowork()$lat, intensity = 20 ,max=40,radius=20,blur=15, gradient = "inferno" , group = "Cluster") %>%
addHeatmap(data = Zweite_Nutzung(), lng= Zweite_Nutzung()$lng,lat= Zweite_Nutzung()$lat, intensity = 20 ,max=40,radius=20,blur=15, gradient = "magma", group = "Cluster 2") %>%
addLayersControl(
baseGroups = c("Kartengrundlage", "Positron Design"),
overlayGroups = c("Standort", "Cluster", "Cluster 2", "Erste Nutzung", "Zweite Nutzung", "Modalität 1", "Modalität 2", "Modalität 1 Nacht", "Modalität 2 Nacht"),
options = layersControlOptions(collapsed = FALSE)) %>%
hideGroup("Cluster") %>%
hideGroup("Cluster 2") %>%
addFullscreenControl(pseudoFullscreen = TRUE)
})
Im more than thankful if somebody could help me.
Great weekend guys!
Sebastian
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.
I want to color map my polygons based on the user input. The column i am using has categorial variables so I am using the colorFactor function which I have tested it is functioning normally. The issue is with the observe function when I load my shiny app it terminates immediately and outputs "Error in addPolygons: unused argument (fillcolor = ~pal(AreaTyp)) in leaflet".My question is how to include reactivity correctly using the observe function. Here is my code:
#INTERACTIVE MAPPING
#colorfunction
pal<-colorFactor(rainbow(7),mp$AreaTyp)
#set data based on user input
fdata<-reactive({
data<-mp
if(input$area!="All"){
data<-data[data$AreaType==input$area,]
}
data
})
output$leaf<-renderLeaflet({
leaflet(fdata()) %>%
#Initializing the map
setView(lng=36.092245, lat=-00.292115,zoom=15)%>%
#Base map
#Add default OpenStreetMap map tiles
addTiles(group = "default")%>%
#addProviderTiles("Esri.NatGeoWorldMap",group = "default")%>%
#addProviderTiles("CartoDB.Positron",group = "custom")%>%
#Overlay map
addPolygons(
data = fdata(),
fillColor = "blue",
weight = 1, smoothFactor = 0.5,
opacity = 1.0, fillOpacity = 1.0,
group = "basepoly",
highlightOptions = highlightOptions(
weight = 2,
color = "red",
fillOpacity = 0.7,
bringToFront = TRUE
),label =~LIA
)
})
observe({
leafletProxy("leaf",data = fdata()) %>%
clearShapes() %>%
addPolygons(
weight = 1, smoothFactor = 0.5,
opacity = 1.0, fillOpacity = 1.0,
data=fdata(),
fillcolor = ~pal(AreaTyp),
label =~LIA
)
})
Change fillcolor = ~pal(AreaTyp) to fillColor = ~pal(AreaTyp)
Let's break down your error.
"Error in addPolygons: unused argument (fillcolor = ~pal(AreaTyp)) in leaflet"
first:
"Error in addPolygons:
this means that addPolygons failed to run. not that the observer failed
second
"unused argument "
This means that you added an argument that addpolygons can not use.
Third
(fillcolor = ~pal(AreaTyp)) in leaflet
This is telling you exactly which argument is wrong.
# 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")
I draw a Polygon on a leafletmap which I use in a shiny app.
Everytime an event is fired I want to delete the old polygon and draw the new one over it.
That does not work - I assume I use layerId wrong?
Any hints on this?
# draw polygons
observeEvent(da$ar, {
# remove polygon
removeShape(map, layerId = unique(10))
leafletProxy("myMap") %>% addPolygons(data = da$ar, stroke = TRUE,
fillOpacity = 0.5, smoothFactor = 0.5,
layerId = unique(10)
)
})
So, I go it.
When you use a layer ID on an object and draw the same object with that layerID again, the object gets deleted.
So, that is enough:
observeEvent(da$ar, {
leafletProxy("myMap") %>% addPolygons(data = da$ar, stroke = TRUE,
fillOpacity = 0.5, smoothFactor = 0.5,
layerId = "foo"
)
})