R sf point Popups inaccessible after adding polygon via simplevis - r

I am trying to create an interactive map (using the simplevis and leaflet packages) to be used in an RMarkdown HTML presentation. The popups work fine when no polygon is added but as soon as the polygon is added the popups can no longer be accessed.
The purpose is to have popups for the sf point data and to only show the legend of the point data. The polygon is added to show the boundries.
How can I fix this?
Sample data and code
library(sf)
library(leaflet)
library(simplevis)
leaf_sf_col(example_point,
col_var = trend_category,
popup = TRUE) %>%
leaflet::addPolygons(data = sf::st_transform(example_borders, 4326),
color = "#35B779",
weight = 3,
fillOpacity = 0,
opacity = 1)

Use addPolylines instead of addPolygons, then the polygon feature won't be capturing the click events (which is what I think is happening) because its only lines instead of an area-covering polygon.

Related

How do I use pictures as custom icons in Leaflet?

I am trying to create an interactive map of football stadiums in the UK with the leaflet package in R. I understand that I can use a custom image as the icon on the map. For a given stadium, I would like to use the badge of the club that plays there as the icon. Initially I am trying to solve the simpler problem of just using one custom image for all the stadiums with the hope that once I can solve this, I will be able to generalise and have one custom image per stadium. I will provide a simplified data set of just two stadiums for the purposes of this question.
So far I have tried using this picture (https://upload.wikimedia.org/wikipedia/en/e/e5/AFC_Bournemouth_%282013%29.svg) of the Bournemouth badge however it does not appear on the map when run. I think R cannot properly access this image but I am not sure what types it can access or how it accesses them.
So far my code looks like this
library(leaflet)
# Create Data
finalData <- data.frame(Club = c("A.F.C. Bournemouth", "A.F.C. Wimbledon"), Latitude = c("50.7352","51.4051"), Longitude = c("-1.83839","-0.281984"), stringsAsFactors = FALSE)
# Create map using leaflet
m <- leaflet() %>%
addTiles()
# Attempt to create custom icon using the linked picture
BournemouthIcon = makeIcon("https://upload.wikimedia.org/wikipedia/en/e/e5/AFC_Bournemouth_%282013%29.svg", iconWidth = 8, iconHeight = 8)
m %>% addMarkers(lat = as.numeric(finalData$Latitude),
lng = as.numeric(finalData$Longitude),
clusterOptions = markerClusterOptions(),
icon = BournemouthIcon)
I expect to see the 2 stadiums plotted on the map with the Bournemouth badge as the marker but instead the markers are blank.1 It appears R knows where to plot the points (since if you zoom out it detects the cluster of points), however it does not know what to mark the point with.2 This links back to my misunderstanding of how R is reading the picture I supplied. Any help with how to properly build a custom marker and then pass it to addMarkers would be greatly appreciated. Furthermore some guidance on generalising this to having a unique custom picture for each marker would also be great!

overlay flux footprint over a map

I need to overlay a plot over a map (it can be from ggmap or from a file in my pc - not a shapefile).
### Here is the map
library(ggmap)
library(RgoogleMaps)
lat = 49.12978
lon = -122.985
center = c(lat, lon)
bbmap <- get_map(location = c(lon, lat), zoom = 18, maptype = "satellite")
And here! is the data and the code to make the plot that I want to overlay.
library(fields)
image.plot(FFP$x_2d[1,],FFP$y_2d[,1],FFP$fclim_2d)
The main problem is that the plot uses distance to a point to generate a flux density plot, so there are no coordinates (I only have the center coordinates which I used to get the map)
This question is pretty much this! that hasn't been answered, but it seems that the solution is georeferencing the data. However, I don't know how to do that in R. I have tried using the "raster" function to create a 3D raster of the map and the image, using the extent of the map for both, but the plot seems not right because it looks like its rotated.
Ultimately, what I want is to have only the 90% or 80% contour line over the map, not the whole thing.
The final image should look something like this but showing only the most external line, reference image: from this webpage
Hope someone can help!
Thanks!

Leaflet Polylines do not show up

I have a very small SpatialLinesDataFrame which I need to plot with Leaflet in R.
Unfortunately, for some reason I'm not able to do so.
This is the data (it's 12KB).
I try to do:
library(leaflet)
load("mylines.Rdata")
leaflet() %>% addTiles() %>% addPolylines(data=mylines)
However the resulting map does not make sense, I can only see a line in the top of the screen and this is not what should be plotted.
This is the result:
Instead, If I do:
library(mapview)
mapview(mylines)
Result:
It works perfectly, despite mapview using leaflet underneath.
What am I doing wrong in the Leaflet syntax?
I am used to working with leaflet providing rasters, so I usually use the addRasterImage function, which needs data projected over leaflet's display projection (EPSG:3857). However, for polygons and lines, as #TimSalabim correctly pointed out, this is not the case.
So the solution in this case was to just not reproject the data to the leaflet projection beforehand, and provide it in lat-lon coordinates (EPSG:4326).
mapview worked since it does this automagically.

addPolygons in leaflet in R shiny destroys reactivity

I am trying to overlay a heatmap of polygons on my map and then be able to zoom into different parts of it depending on user input.
The code works fine when I remove the heatmap. The user is able to jump around from place to place (based on a dropdown list).
With the polygons it works the first time fully,
the second dropdown choice causes just a map to show with no polygons and the location does not shift,
and the third dropdown choice nothing shows.
output$HMmapstation <- renderLeaflet({
x <- NA
x <- input$HMstation #picking the place to view
x <- leaflet_map %>% setView(preloaded_stations[which(preloaded_stations$name == x),]$longitude,
preloaded_stations[which(preloaded_stations$name == x),]$latitude,
zoom = 14) %>% clearShapes()
x <- x %>% addPolygons(data=polys_dat, color = ~pal(polys_dat#plotOrder),
smoothFactor=.1, stroke = FALSE, fillOpacity = 0.1)
x
})
The leaflet map is created globally above the server and is as follows:
leaflet_map <- (leaflet() %>%
addProviderTiles("OpenStreetMap.BlackAndWhite",
options = providerTileOptions(noWrap = TRUE,minZoom=9)) %>%#~pal(seq(1,537,1))~rainbow(50, start=0,end=.3, alpha = NULL)
setMaxBounds(-0.715485, 51.252031, 0.514984, 51.745313))
I just cant seem to figure out why it would work once and then stop. Especially since without the polygon it works as expected.
Thank you in advance for any direction you can give me.
Leaflet is an amazing addition to R's quiver, I am starting to use it quite a bit at work and at times I also struggle with lost functionality as layers build. I do not have an answer for you working directly in R, but I have a suggestion.
One of the things that I am discovering as I become a Javascript D3 developer is that the last object into a JS visualization is on top.
So this means as you stack polygons, lines, and other objects and data onto a map, it is possible to BLOCK the visibility/functionality of objects below it.
If you are familiar with Javascript, you could open the devtools in chrome and look to see how the layers are being applied to the map.
As you do this, try to think about how R will call out to JS to compile the web graphic it makes and then see if you can re-order something in your R stack, or turn a shape into an outline so that the shape below retains function.
And it is possible after the graphic is "extruded' from R to go in and manually tweak the javascript controlling the features you are using with a lot more control than you have in R itself. I have done some editing on the resulting file set successfully.
There is a LOT more help in working on leaflet in JS directly here and around the web. You may be able to find a quicker answer that way.
The fix ended up being to put the leaflet in a reactive rather than a renderLeaflet.
I also re-ordered based on bethanyP's response so thank you!

Overlaying shapefiles or raster over interactive maps

I'm using R, and I want to overlay some raster data (e.g. a temperature map from a model) over an interactive map which allows panning and zooming. Ideally, I'd like to overlay over Google Maps or OpenStreetMaps. The input data can be in shapefiles, KML, raster data or whatever comes in handy.
I know I can easily do this non-interactively using either googleVis, ggmap or RgoogleMaps. But I do not want to use tiles, I want interaction! Zooming, panning etc., directly from the browser.
googleVis, as far as I know, unfortunately only allows to show interactively points or addresses, not areas.
This question is very similar but I definitely want to try to do this using R. I can create the KML or geoJSON from R, but how do I overlay it from R directly?
OpenStreetMaps is also fine, however I've not found any reference on how to overlay data over it from R, despite the fact that OSM seems to have a pretty straightforward API.
The mapview package has been developed for this particular purpose. It also comes with a variety of background map layers. For a short introduction to what mapview is capable of, feel free to browse the package vignette. Here, for example, is some code that displays locations of selected breweries in Franconian Switzerland overlaid by a sample Landsat 8 scene (band 10). Check out ?breweries91 and ?poppendorf to retrieve information about the data used below and ?mapview to grow familiar with the numerous costumization options.
## require package
# install.packages("mapview")
library(mapview)
## visualize breweries and add landsat 8 band 10
mapview(breweries91) +
poppendorf[[10]]
The leaflet package may be of interest for you. You can easily add a raster object. From the documentation
Two-dimensional RasterLayer objects (from the raster package) can be
turned into images and added to Leaflet maps using the addRasterImage
function.
And here is an example also from the documentation:
library(leaflet)
library(raster)
r <- raster("nc/oisst-sst.nc")
pal <- colorNumeric(c("#0C2C84", "#41B6C4", "#FFFFCC"), values(r),
na.color = "transparent")
leaflet() %>% addTiles() %>%
addRasterImage(r, colors = pal, opacity = 0.8) %>%
addLegend(pal = pal, values = values(r),
title = "Surface temp")

Resources