R Leaflet Label Set direction - r

Please have a look at the below example code, I would like to use the label direction (MyDirection), which is stored in df to have different label directions within my map.
I can set every label to a specific direction like direction = "top", but somehow its not working if I specify direction = ~MyDirection.
Any Idea/solution would be much appreciated.
Thanks in advance.
library(leaflet)
df <- read.csv(textConnection("
Name,Lat,Long,MyDirection
ANN,51.19,4.46277778,right
BAB,43.26306,-2.94972222,left
BCN,41.29694,2.07833333,top
BCN,41.29694,2.07833333,bottom
"))
#---Create Map----
m <- leaflet(df) %>%
addTiles(group = "OSM (default)") %>%
addCircles(~Long, ~Lat,
label = ~htmlEscape(Name),
labelOptions = labelOptions(noHide = T,
#direction = "top",
#direction = "bottom",
#direction = "left",
#direction = "right",
direction = ~MyDirection))
m

I would like to share my latest approach. I finally managed to set the label direction based on mydf$MyDirection. Instead of adding multiple layers, as i did in my previous example, I used the library "Purrr". This reduces the amount of layers tremendously.
Best Regards
#Libraries----
library(leaflet)
library(htmltools)
library(htmlwidgets)
library(purrr)
#---Data Input----
mydf <- read.csv(textConnection("
Facility,Lat,Long,MyDirection
ANN,51.19,4.46277778,right
BAB,43.26306,-2.94972222,left
BCN,41.29694,2.07833333,top
BCN2,41.29694,2.07833333,bottom
"))
#---Create Vector----
ob_Facility <- mydf %>%
split(., .$Facility)
#---Create Map----
m <- leaflet() %>%
addTiles()
#---Purrr Layers----
names(ob_Facility) %>%
purrr::walk(function(mydf) {
m <<- m %>%
addCircleMarkers(data=ob_Facility[[mydf]],
lng=~Long, lat=~Lat,
group = "Show All",
label = ~Facility,
labelOptions = labelOptions(noHide = T,direction = ~MyDirection))
})
#---Layers control----
m %>%
addLayersControl(
overlayGroups = "Show All",
options = layersControlOptions(collapsed = FALSE)
)%>%
#---Save as HTML File----
saveWidget('Example Go Live Date.html', selfcontained = TRUE)

Hello,
I have figured out a workaround with 4 Layers (top,bottom,left,right) and attached the same group name to each layer.
library(leaflet)
df <- read.csv(textConnection("
Name,Lat,Long,MyDirection
ANN,51.19,4.46277778,right
BAB,43.26306,-2.94972222,left
BCN,41.29694,2.07833333,top
BCN,41.29694,2.07833333,bottom
"))
#---Create 4 additional DFs (1 for each dirction)----
dfLeft = df[df$MyDirection == "left", ]
dfRight = df[df$MyDirection == "right", ]
dfTop = df[df$MyDirection == "top", ]
dfBottom = df[df$MyDirection == "bottom", ]
#---Create Map----
m <- leaflet(df) %>%
addTiles(group = "OSM (default)") %>%
addCircles(~dfLeft$Long, ~dfLeft$Lat, color = '#d40511',
label = ~htmlEscape(dfLeft$Name),
labelOptions = labelOptions(noHide = T,
direction = "left"),
group = "Show All")%>%
addCircles(~dfRight$Long, ~dfRight$Lat, color = '#d40511',
label = ~htmlEscape(dfRight$Name),
labelOptions = labelOptions(noHide = T,
direction = "right"),
group = "Show All")%>%
addCircles(~dfTop$Long, ~dfTop$Lat, color = '#d40511',
label = ~htmlEscape(dfTop$Name),
labelOptions = labelOptions(noHide = T, direction = "top",
offset = c(0, -2)),
group = "Show All")%>%
addCircles(~dfBottom$Long, ~dfBottom$Lat, color = '#d40511',
label = ~htmlEscape(dfBottom$Name),
labelOptions = labelOptions(noHide = T, direction = "bottom",
offset = c(0, 2)),
group = "Show All")
m

Related

R: Connecting Dots on a Map

I am working with the R programming language.
Using the "leaflet" library, I made the following map for these 5 cities:
library(dplyr)
library(leaflet)
map_data <- data.frame("Lat" = c(43.6426, 43.6424, 43.6544, 43.6452, 43.6629), "Long" = c(-79.3871, -79.3860, -79.3807, -79.3806,-79.3957 ), type = c(1,2,3,4,5))
map_data$type = as.factor(map_data$type)
leaflet(map_data) %>%
addTiles() %>% addCircleMarkers(stroke = FALSE, label = ~type,fillOpacity = 0.8, labelOptions = labelOptions(direction = "center",style = list('color' = "white"),noHide = TRUE, offset=c(0,0), fill = TRUE, opacity = 1, weight = 10, textOnly = TRUE))
On this above map that I have created, I would now like to "connect" all these "points" (i.e. cities) on the map (in a route) based on their "number" (e.g. connect 1 with 2, 2 with 3, 3 with 4, 4 with 5, 5 with 1), and output the "total distance" of the route. I found a previous post that shows how to do this: How to show path and distance on map with leaflet, shiny apps?
I tried to adapt the code from this post to suit my question:
library(osrm)
route = osrmRoute(c(-79.3871, -79.3860, -79.3807, -79.3806,-79.3957 ), c(43.6426, 43.6424, 43.6544, 43.6452, 43.6629), overview = 'full')
route_summary = osrmRoute(c(-79.3871, -79.3860, -79.3807, -79.3806,-79.3957 ), c(43.6426, 43.6424, 43.6544, 43.6452, 43.6629), overview = FALSE)
leaflet() %>% addTiles() %>%
addCircleMarkers(c(-79.3871, -79.3860, -79.3807, -79.3806,-79.3957 ), c(43.6426, 43.6424, 43.6544, 43.6452, 43.6629), stroke = FALSE, label = ~type,fillOpacity = 0.8,
labelOptions = labelOptions(direction = "center",style = list('color' = "white"),noHide = TRUE, offset=c(0,0), fill = TRUE, opacity = 1, weight = 10, textOnly = TRUE)) %>%
addPolylines(route$lon,route$lat,
label = paste(round(route_summary[1]/60), 'hr - ', round(route_summary[2]), 'km'),
labelOptions = labelOptions(noHide = TRUE))
But this returns the following error:
Error in UseMethod("metaData") :
no applicable method for 'metaData' applied to an object of class "NULL"
Can someone please show me how to fix this problem?
I would like to do this using "leaflet" and not using "rshiny". In the end, I would like the final map to look something like this (this is supposed to represent a "single path" from a Travelling Salesman Problem) :
[![enter image description here][2]][2]
Note: I am starting to think that problem might be that the "osrmRoute()" function might not be able to work for more than 2 points?
https://github.com/riatelab/osrm/issues/41
https://rdrr.io/cran/osrm/man/osrmTrip.html
One way is for you to make API call:
https://github.com/Project-OSRM/osrm-backend/blob/master/docs/http.md
I'll just outline how can you do it:
data
df <- data.frame(
lon = c(-79.3871, -79.3860, -79.3807, -79.3806,-79.3957),
lat = c(43.6426, 43.6424, 43.6544, 43.6452, 43.6629)
)
url call
root <- "http://router.project-osrm.org/route/v1/driving/"
options <- c(
continue_straight = "true",
overview = "full",
annotations = "true",
steps = "true"
)
coords <- df %>%
slice(c(seq_len(n()), 1)) %>%
pmap_chr(str_c, sep = ",") %>% str_c(collapse = ";")
options <- options %>%
imap_chr(~str_c(.y, "=", .x)) %>%
str_c(collapse = "&") %>%
str_c("?", .)
res <- rjson::fromJSON(file = str_c(root, coords, options))
Note that I've added first point as 6th row to make circle route.
map
res$routes[[1]]$geometry %>%
googlePolylines::decode() %>%
.[[1]] %>%
leaflet() %>%
addTiles() %>%
addPolylines(lng = ~lon, lat = ~lat) %>%
addCircleMarkers(
data = df,
stroke = FALSE,
label = seq_len(nrow(df)),
fillOpacity = 0.8,
labelOptions = labelOptions(
direction = "center",
style = list('color' = "white"),
noHide = TRUE,
offset=c(0,0),
fill = TRUE,
opacity = 1,
weight = 10,
textOnly = TRUE
)
)
distance
res$routes[[1]]$distance
This is in meters (documentation)
EDIT
There probably is better way of labeling polyline but I don't have time now:
library(sf)
segment_df <- df %>% rbind(df[1,])
d <- segment_df %>%
st_as_sf(coords = c("lon", "lat"), crs = 4326) %>%
{st_distance(.[-6,], .[-1,], by_element = TRUE)} %>%
as.vector() %>%
round()
m <- leaflet() %>% addTiles()
for(i in seq_len(nrow(segment_df) - 1))
m <- m %>% addPolylines(
data = segment_df[i:(i+1),],
lng = ~lon, lat = ~lat, color = "red", label = paste(d[[i]], "m"),
labelOptions(noHide = TRUE, direction = 'top')
)
m <- m %>% addCircleMarkers(
data = df,
stroke = FALSE,
label = seq_len(nrow(df)),
fillOpacity = 0.8,
labelOptions = labelOptions(
direction = "center",
style = list('color' = "white"),
noHide = TRUE,
offset=c(0,0),
fill = TRUE,
opacity = 1,
weight = 10,
textOnly = TRUE
)
)
If you want only to show total distance then that is easier and does not require loop, just replace loop with:
segment_df %>%
leaflet() %>%
addTiles() %>%
addPolylines(
lng = ~lon, lat = ~lat, color = "red",
label = paste(sum(d), "m"),
labelOptions = labelOptions(noHide = TRUE, direction = 'top')
)
I hope you understand (and see from map) that this is not drivable.
Here is an answer I tried based on #det's answer:
library(sf)
library(geosphere)
library(dplyr)
library(leaflet)
library(data.table)
library(VPF)
#add a 6th row that is equal to the 1st row - so that the path loops back
map_data <- data.frame("Lat" = c(43.6426, 43.6424, 43.6544, 43.6452, 43.6629, 43.6426), "Long" = c(-79.3871, -79.3860, -79.3807, -79.3806,-79.3957, -79.3871 ), type = c(1,2,3,4,5,1))
map_data$type = as.factor(map_data$type)
m1 = leaflet(map_data) %>% addTiles() %>% addCircleMarkers(stroke = FALSE, label = ~type,fillOpacity = 0.8,
color = ~ifelse(type==1,"red","blue"), labelOptions = labelOptions(direction = "center",style = list('color' = "white"),
noHide = TRUE, offset=c(0,0), fill = TRUE, opacity = 1, weight = 10, textOnly = TRUE))
m1 %>% addTiles() %>%
addPolylines(data = map_data, lng = ~Long, lat = ~Lat, group = ~type)
Now, I want to calculate the total distance of the trip and have it displayed on the map:
#distances (https://stackoverflow.com/questions/42119438/calculate-distance-between-two-long-lat-coordinates-in-a-dataframe)
result = rbind(
cbind(map_data[1:nrow(map_data)-1,c(1,2)], map_data[-1,c(1,2)]),
cbind(map_data[nrow(map_data), c(1,2)], map_data[1,c(1,2)])
)
colnames(result) <- c("start_lat", "start_long", "end_lat", "end_long")
result$id = as.factor(c(1,2,3,4,5,1))
result = data.frame(result)
for (i in 1:nrow(result)) {
a<-result$start_long[i]
b<-result$start_lat[i]
c<-result$end_long[i]
d<-result$end_lat[i]
result$distance[i]<-distm(c(a,b),c(c,d), fun = distHaversine)
}
#total distance of trip in meters
d = result$distance
total_d = signif(sum(d),3)
m1 %>% addPolylines(
data = map_data,
lng = ~Long, lat = ~Lat, color = "blue", label = paste0(total_d, " meters"),
labelOptions(noHide = TRUE, direction = 'top')
)
I think I finally got it - thanks so much # Det!

Leaflet with Shiny - how to ensure maximum zoom in option for the user

For one of the map use case , need to provide maximum zoom in option for the user in shiny app. Have tried to explore some of the options as per below code. Wanted to understand if this is the maximum limit we can have in shiny app using leaflet or I am missing something , really appreciate some guidance here.
One of the reactjs web application , Zoom In is possible even further - Here we are using bing / google map license though.
field <- raster::shapefile("sampleShapleFile.shp") # shapefile (field) imported
library(leaflet)
library(leaflet.extras)
leaflet(data = field ,
options = leafletOptions(zoomSnap = 0.25, zoomDelta = 0.25)) %>%
addFullscreenControl(position = "topleft", pseudoFullscreen = FALSE) %>%
addBingTiles(
"Aq4GyoG8kzfeKO7Nsav5_BcjVVA_d1ULSTeXeW2zM0aPuANIqhvV5IrFtMjOGX3s",
imagerySet = c("AerialWithLabels"),
group = "AerialWithLabels",
options = tileOptions(minZoom = 0, maxZoom = 18)
) %>%
addPolygons(
fill = FALSE,
stroke = TRUE,
weight = 5,
opacity = 1,
color = "#FFFFFF"
) %>%
addLegend("bottomright", color = "#FFFFFF", labels = "Test") %>%
addMeasure(
position = "bottomleft",
primaryLengthUnit = "meters",
primaryAreaUnit = "sqmeters",
activeColor = "#10bae0",
completedColor = "#241ad9"
) %>%
addDrawToolbar(
targetGroup = 'draw',
polygonOptions = FALSE,
circleOptions = FALSE,
rectangleOptions = FALSE,
markerOptions = FALSE,
circleMarkerOptions = FALSE,
editOptions = editToolbarOptions(selectedPathOptions = selectedPathOptions())
) %>%
addScaleBar(position = "topright",
options = scaleBarOptions(
maxWidth = 1,
metric = TRUE,
imperial = FALSE
))
"maxNativeZoom" with "maxZoom" Option in "addTiles" can be utilized to enhance zoom in level for Google / Bing Map
Useful Reference Links :
https://gis.stackexchange.com/questions/78843/zoom-further-in-than-level-19-with-leaflet-javascript-api
https://github.com/digidem/leaflet-bing-layer/issues/8
## app.R ##
library(shiny)
library(shinydashboard)
library(leaflet)
library(leaflet.extras)
ui <- dashboardPage(dashboardHeader(),
dashboardSidebar(),
dashboardBody(leafletOutput("map")))
server <- function(input, output) {
field <-
raster::shapefile("sample.shp") # shapefile (field) imported
output$map <- renderLeaflet({
leaflet(data = field) %>%
addFullscreenControl(position = "topleft", pseudoFullscreen = FALSE) %>%
# addTiles(
# group = "Satellite",
# urlTemplate = "http://mt0.google.com/vt/lyrs=s&hl=en&x={x}&y={y}&z={z}&s=Ga",
# options = tileOptions(maxZoom = 21 , maxNativeZoom = 18)
# ) %>%
addBingTiles("Aq4GyoG8kzfeKO7Nsav5_BcjVVA_d1ULSTeXeW2zM0aPuANIqhvV5IrFtMjOGX3s",
imagerySet = c("AerialWithLabels"),group = "AerialWithLabels",
maxNativeZoom = 18,maxZoom = 21
) %>%
addPolygons(
fill = FALSE,
stroke = TRUE,
weight = 5,
opacity = 1,
color = "#FFFFFF"
) %>%
addLegend("bottomright", color = "#FFFFFF", labels = "Test") %>%
addMeasure(
position = "bottomleft",
primaryLengthUnit = "meters",
primaryAreaUnit = "sqmeters",
activeColor = "#10bae0",
completedColor = "#241ad9"
) %>%
addDrawToolbar(
targetGroup = 'draw',
polygonOptions = FALSE,
circleOptions = FALSE,
rectangleOptions = FALSE,
markerOptions = FALSE,
circleMarkerOptions = FALSE,
editOptions = editToolbarOptions(selectedPathOptions = selectedPathOptions())
) %>%
addScaleBar(
position = "topright",
options = scaleBarOptions(
maxWidth = 10,
metric = TRUE,
imperial = FALSE
)
)
})
}
shinyApp(ui, server)

How to show/hide legend with control layer panel with leaflet?

I am trying to plot a map with multiple layers. However, when selecting the group I want to show in the controlLayer panel, it changes the map but not the legend. In fact, the 2 legends are always displayed together on the map, but I only want one of them at a time.
Here is the code I use :
leaflet(data) %>%
addProviderTiles("Esri.WorldStreetMap") %>%
addRasterImage(r, opacity = 1, colors = cb, group = "Predictions") %>%
addLegend(pal = cb, values = wind_speed_range, title = "Wind Speed", opacity = 1, group = "Predictions", position = "topright") %>%
addCircles(radius = ~ residual*7000, color = "black", fillColor = ~ cb(predictions), fillOpacity = 1, label = ~ paste(as.character(residual), " / ", as.character(vitesse_vent), " / ", as.character(predictions)), weight = 2, group = "Predictions") %>%
addRasterImage(raster_difference, opacity = 1, colors = cb_correction, group = "Corrections") %>%
addLegend(pal = cb_correction, values = correction_range, title = "Corrections", opacity = 1, group = "Corrections", position = "topright") %>%
addLayersControl(
baseGroups = c("Prédictions", "Corrections"),
options = layersControlOptions(collapsed = FALSE),
position = "topleft"
)
As you can see, I already tried the solution of this post. I also tried with overlayGroup instead of baseGroup, but the problem is still here.
The image below is what I get using this code :
You can clearly see the two legends.
Code
Unfortunately, you did not provide a reprex, so I show it with a made up example:
library(leaflet)
cities1 <- data.frame(City = factor(c("Boston", "Hartford",
"New York City", "Philadelphia", "Pittsburgh", "Providence")),
Lat = c(42.3601, 41.7627, 40.7127, 39.95, 40.4397, 41.8236),
Long = c(-71.0589, -72.6743, -74.0059, -75.1667, -79.9764, -71.4222),
Pop = c(645966L, 125017L, 8406000L, 1553000L, 305841L, 177994L),
Type = factor(c("C", "D", "A", "A", "B", "C")))
cities2 <- data.frame(City = factor(c("Baltimore", "Ithaca", "Wareham")),
Lat = c(39.299236, 42.443962, 41.761452),
Long = c(-76.609383, -76.501884, -70.719734),
Pop = c(609032L, 30569L, 22666L),
Type = factor(letters[1:3]))
pal1 <- colorFactor("viridis", domain = cities1$Type)
pal2 <- colorFactor("Set1", domain = cities2$Type)
leaflet(cities1) %>%
addTiles() %>%
addCircles(data = cities1, lng = ~Long, lat = ~Lat, weight = 1, group="one",
radius = ~sqrt(Pop) * 30, popup = ~City, color = ~pal1(Type), opacity = .9
) %>%
addLegend(pal = pal1, values = ~Type, group = "one", layerId = "one") %>%
addCircles(data = cities2, lng = ~Long, lat = ~Lat, weight = 1, group = "two",
radius = ~sqrt(Pop) * 30, popup = ~City, color = ~pal2(Type), opacity = .9
) %>%
addLegend(pal = pal2, values = ~Type, data = cities2, group = "two", layerId = "two") %>%
addLayersControl(
baseGroups = c("one", "two"),
options = layersControlOptions(collapsed = FALSE),
position = "topleft"
) %>%
htmlwidgets::onRender("
function() {
var map = this;
var legends = map.controls._controlsById;
function addActualLegend() {
var sel = $('.leaflet-control-layers-base').find('input[type=\"radio\"]:checked').siblings('span').text().trim();
$.each(map.controls._controlsById, (nm) => map.removeControl(map.controls.get(nm)));
map.addControl(legends[sel]);
}
$('.leaflet-control-layers-base').on('click', addActualLegend);
addActualLegend();
}")
Explanation
You can define some custom JavaScript which reacts upon the changes of the radio buttons. When they change, I basically delete all controls and add the selected. In order for this to work, I need to save a copy of the controls first. This is of course a bit hackish (especially since I am accessing the "private" _controlsById slot of the map), but from my quick scan of the leaflet API I did not find a better entry point.
Screenshot

Firefox Leaflet Not Displaying Map Shapes in Shiny App Default Page When Published on shinyapps.io (other browsers are working fine)

I've just created my first Shiny app and published to the Internet - https://craycrayjodie.shinyapps.io/MapApp/
When launching the app and viewing in Chrome and I.E the default page ('Map' tab) loads as expected - with the "March" data displayed on the map. This is specified in the sliderTextInput for the page.
However, when I load the app and view in Firefox (i.e. the 'Map' tab), the "March" data is not displayed on the map when the app loads by default in Firefox. I need to move the sliderTextInput, then the data loads on the map in the Browser.
This is only an issue for Firefox, the other browsers (i.e. Chrome and IE) are fine and have the March data loaded and displayed on the map when the default 'Map' page loads.
I have published my files up to GitHub - https://github.com/craycrayjodie/DataVis
Also, my app.R logic is as follows:
library(dplyr)
library(lubridate)
library(sf)
library(leaflet)
library(shinythemes)
library(RColorBrewer)
library(shinyWidgets)
library(rmapshaper)
library(rsconnect)
library(shiny)
library(ggplot2)
library(highcharter)
library(magrittr)
library(htmlwidgets)
library(RColorBrewer)
library(shinycssloaders)
###################################################################################################
myAusdata_by_month_sf = readRDS("myAusdata_by_month.rds") #load previously saved datafile
myAusdata_by_month_5 = readRDS("myAusdata_by_month_5.rds") #load previously saved datafile
areas_by_weeks = readRDS("areas_by_weeks.rds") #load previously saved datafile
# Options for Spinner
options(spinner.color="pink", spinner.type = 7, spinner.color.background="#ffffff", spinner.size=1)
ui <- shinyUI(
navbarPage(
title = "Australians Mobility Changes During COVID",
theme = shinytheme("yeti"),
tabPanel("Map",
div(class = "outer",
tags$head(
includeCSS("styles.css")
),
leafletOutput("map", width = "100%", height = "100%"),
absolutePanel(bottom = 30, left = 250, draggable = TRUE,
# slider title, step increments
sliderTextInput("choices", "Select month:", choices = unique(myAusdata_by_month_sf$month),
animate = animationOptions(interval = 1500, loop = FALSE), grid = TRUE, selected = "March", width = 400))
),
tags$div(id = "cite",
'Data downloaded from Facebook for Good by Jodie Anderson (2020).'
)
),
tabPanel("Story",
highchartOutput("timeline", height = "800px" ) %>% withSpinner(),
includeMarkdown("analysis.md"),
br()
),
tabPanel("Heatmap",
highchartOutput("heatmap", height = "100%") %>% withSpinner(),
br()
),
tabPanel("About",
includeMarkdown("about.md"),
br()
)
)
)
# Define server logic
server <- function(input, output, session) {
filteredData <- reactive({
myAusdata_by_month_sf %>%
filter(month %in% input$choices)
})
popup <- reactive({
sprintf("%s: %.1f%%", filteredData()$polygon_name, filteredData()$AvRelChange*100)
})
output$map <- renderLeaflet({
mypalette <- colorNumeric(palette = "PuOr", domain = myAusdata_by_month_sf$AvRelChange, na.color = "transparent")
leaflet(myAusdata_by_month_sf) %>%
setView(134, -29, 4) %>%
addProviderTiles("Esri.WorldGrayCanvas") %>%
addLegend(pal=mypalette, values=~AvRelChange, opacity=1, title = "Mobility Change (%)", position = "bottomleft",
labFormat = labelFormat(prefix = "(", suffix = ")", between = ", ",
transform = function(x) 100 * x))
})
observe({
mypalette <- colorNumeric(palette = "PuOr", domain = myAusdata_by_month_sf$AvRelChange, na.color = "transparent")
leafletProxy("map", data = filteredData()) %>%
clearShapes() %>%
addPolygons(fillColor = ~mypalette(AvRelChange),
stroke=TRUE,
fillOpacity = 1,
color = "grey",
weight = 0.3,
label = popup(), labelOptions = labelOptions(
style = list("font-weight" = "normal", padding = "2px 2px"),
textsize = "13px",
direction = "auto", offset = c(20, -25)))
})
output$timeline <- renderHighchart ({
hc <- myAusdata_by_month_5 %>%
hchart ('spline', hcaes(x= date, y=AvRelChange, group=NAME_1)) %>%
hc_colors(brewer.pal(8, "Dark2")) %>%
hc_title(text="Australians Mobility Changes", style=list(fontWeight="bold", fontSize="30px"),
align="left") %>%
hc_subtitle(text="During the coronavirus pandemic", style=list(fontWeight="bold"), align="left") %>%
hc_xAxis(title = list(text=NULL), plotBands = list(list(label = list(text = "Australia<br>in<br>lockdown"), color = "rgba(100, 0, 0, 0.1)",from = datetime_to_timestamp(as.Date('2020-03-16', tz = 'UTC')),
to = datetime_to_timestamp(as.Date('2020-03-31', tz = 'UTC'))))) %>%
hc_yAxis(title=list(text = "Mobility Change (%)"), showLastLabel = FALSE, labels = list(format = "{value}%")) %>%
hc_caption(text = "The Change in Mobility metric looks at how much people are moving around and compares it to a baseline period that predates most social distancing measures.<br>
The baseline period for this dataset is the four weeks of February 2020 (i.e. from the 2nd to the 29th).", useHTML = TRUE)%>%
hc_credits(text = "www.highcharts.com", href = "www.highcharts.com", enabled = TRUE, style = list(fontSize="10px")) %>%
hc_tooltip(crosshairs = TRUE, borderWidth = 2, valueSuffix = "%") %>%
hc_navigator(enabled = TRUE) %>%
hc_rangeSelector(enabled = TRUE) %>%
hc_plotOptions(series = list(marker = list(enabled = FALSE), lineWidth = 4)) %>%
hc_add_annotation(labels = list(list(point = list(xAxis = 0,yAxis = 0,x = datetime_to_timestamp(as.Date('2020-07-13', tz = 'UTC')),y = 7),shape = "rect", text = "10th July: QLD opens borders", useHTML = TRUE))) %>%
hc_add_annotation(labels = list(list(point = list(xAxis = 0,yAxis = 0,x = datetime_to_timestamp(as.Date('2020-07-20', tz = 'UTC')),y = -22),shape = "rect", text = "30th June: Vic in lockdown", useHTML = TRUE))) %>%
hc_add_annotation(labels = list(list(point = list(xAxis = 0,yAxis = 0,x = datetime_to_timestamp(as.Date('2020-08-20', tz = 'UTC')),y = -30),shape = "rect", text = "2nd Aug: Vic restrictions ease", useHTML = TRUE))) %>%
hc_add_annotation(labels = list(list(point = list(xAxis = 0,yAxis = 0,x = datetime_to_timestamp(as.Date('2020-11-14', tz = 'UTC')),y = -41),shape = "rect", text = "16th Nov: SA restrictions in place<br>21st Nov: SA restrictions lifted", useHTML = TRUE)))
hc
})
output$heatmap <- renderHighchart ({
hc1 <- areas_by_weeks %>%
hchart(type = "heatmap", hcaes(x = date, y = polygon_name, value = AvRelChange)) %>%
hc_title(text="Australians Mobility Changes", style=list(fontWeight="bold", fontSize="30px"), align="left") %>%
hc_subtitle(text="During the coronavirus pandemic", style=list(fontWeight="bold"), align="left") %>%
hc_boost(useGPUTranslations = TRUE) %>%
hc_size(height = 5000, width = 550) %>%
hc_colorAxis(labels = list(format = '{value}%'), stops = color_stops(10, rev(brewer.pal(10, "RdBu")))) %>%
hc_legend(itemMarginTop = 75, layout = "vertical", verticalAlign = "top", align = "right", valueDecimals = 0) %>%
hc_xAxis(labels = list(enabled = FALSE), tickInterval = 5, title = NULL, lineWidth = 0, tickLength = 20) %>%
hc_yAxis(title=list(text = ""), reversed = TRUE, gridLineWidth = 0) %>%
hc_tooltip(pointFormat = '{point.date} <br> {point.polygon_name}: <b>{point.value} %') %>%
hc_credits(position = list(align = 'center', x = 135, y = -4), text = "www.highcharts.com", href = "http://www.highcharts.com", enabled = TRUE, style = list(fontSize="10px")) %>%
hc_caption(align = 'center', text = "The white coloured boxes in the heatmap represent gaps in data.", useHTML = TRUE)
hc1
})
}
# Run the application
shinyApp(ui = ui, server = server)
If a clever cookie can please advise on what changes I need to make to get the app working when the page loads with Firefox, that would be fabulous :)

Weird Leaflet Map Legend Display

pal <- colorFactor(palette = "Set1", domain = MFT_tidy$Parent_Organization)
popup_text <- paste(MFT_tidy$Facility_Name, "<br>",
"Facility_Phone:", MFT_tidy$Facility_Phone, "<br>",
"Vendor_Name:", MFT_tidy$Vendor_Name)
layer_groups <- c("OSM (default)", "Toner", "Positron", "NatGeoWorldMap")
leaflet(MFT_tidy, width = "100%") %>%
addTiles(group = "OSM (default)") %>%
addProviderTiles(providers$Stamen.Toner, group = "Toner") %>%
addProviderTiles(providers$CartoDB.Positron, group = "Positron") %>%
addProviderTiles(providers$OpenTopoMap, group = "OpenTopoMap") %>%
addProviderTiles(providers$Esri.NatGeoWorldMap, group = "NatGeoWorldMap") %>%
addCircleMarkers(lng = ~longitude, lat = ~latitude,
color = ~pal(Parent_Organization),
stroke = FALSE, fillOpacity = 1,
label = ~Facility_Name,
popup = popup_text,
clusterOptions = markerClusterOptions() ) %>%
addLegend(position = "topright", pal = pal,
values = ~Parent_Organization,
labels = ~Parent_Organization,
title = "Parent Organization",
opacity = 1) %>%
addLayersControl(baseGroups = c("OSM (default)", "Toner", "Positron",
"OpenTopoMap", "NatGeoWorldMap"),
position = "bottomright") %>%
addMeasure(
position = "bottomleft",
primaryLengthUnit = "meters",
primaryAreaUnit = "sqmeters",
activeColor = "#3D535D",
completedColor = "#7D4479") %>%
addEasyButton(easyButton(
icon = "fa-globe", title = "Zoom to Original Level",
onClick = JS("function(btn, map){ map.setZoom(6); }"))) %>%
addEasyButton(easyButton(
icon = "fa-crosshairs", title = "Locate Me",
onClick = JS("function(btn, map){ map.locate({setView: true}); }")))
The code I used to create the map is as above:
There are obvious something wrong with the weird display of legend. I do not know how to correct it. I really cannot find anything wrong in the addLegend function.
Possible duplicate.
Problem is not with the addLegend function, but rather the zoom in the browser. You can fix this by adjusting CSS on the legend
Copying #Adam's code:
ui <- bootstrapPage(
tags$style(type="text/css", "div.info.legend.leaflet-control br {clear: both;}"),
...
)

Resources