R leaflet addRasterImage doesn't work at zooms higher than 18 - r

I am wanting to use the addRasterImage() function to a leaflet object in R.
However it only seems to work up-to a zoom level of 18. Please see the example below.
library(raster)
library(leaflet)
library(magrittr)
r <- raster(xmn=-2.8, xmx=-2.79, ymn=54.04, ymx=54.05, nrows=30, ncols=30)
values(r) <- matrix(1:900, nrow(r), ncol(r), byrow = TRUE)
crs(r) <- CRS("+init=epsg:4326")
leaflet() %>% addTiles() %>%
setView(lat=54.045,lng=-2.795,zoom=19) %>%
addRasterImage(r, colors = "Spectral", opacity = 0.8)
I know that the addTiles() function naturally only shows tiles up to a zoom of 18, but I was assuming that the raster image should still show at the higher zoom level. Furthermore, there are other tile providers (e.g. HERE) that do have zoom levels that go higher than 18, but the issue with the lack of the Raster image on the leaflet object still persists.
Any help would be greatly appreciated.

Related

Locking the zoom in on Mapview?

I am creating a map plotted with points around the UK map with map view library in R. I want to have a fixed zoom or zoom button disabled. I don't want a Street view/Zoom in due to GDPR issues. I wonder if there is a solution for this? Thanks.
library(sf)
library(mapview)
mapview(datamap, xcol = "Longitude", ycol = "Latitude")
This is not possible with mapview and kinda defeats the purpose of the package. If you want this type of behaviour you either need to create the complete map using leaflet or at least create the base map with leaflet and then use it with mapview:
library(mapview)
library(leaflet)
map = leaflet(options = leafletOptions(minZoom = 12, maxZoom = 12)) %>%
addTiles()
mapview(franconia, map = map)

Export leaflet map with fixed zoom and bounding box without padding

I know that I can use mapview::mapshot to export a leaflet map from Rstudio as a PNG. I have not been, however, able to precisely specify the zoom level and region of the map to be exported.
Borrowing some code from this answer to a related question let us consider the following MWE.
library(maps)
library(ggmap)
library(maptools)
library(leaflet)
library(mapview)
library(rgdal)
country <- 'italy';
zoomLevel <- 12;
ita.map <- map( country, fill = TRUE, col = 1, plot = F );
ita.map.ids <- sapply( strsplit( ita.map$names, ':' ), function(x) x[1] );
ita.sp <- map2SpatialPolygons( ita.map, IDs=ita.map.ids, proj4string=CRS("+proj=longlat +datum=WGS84"))
bb<-as.numeric(ita.sp#bbox)
m<-leaflet() %>%
setView(12.48,41.89,zoom=zoomLevel) %>%
addTiles() %>%
addPolygons(data=ita.sp)%>%
addExtent(data=ita.sp)
mapshot(m, file = "italy.png")
results in This is the correct zoom level but clearly does not contain all of Italy.
Adding
%>% fitBounds(bb[1],bb[2],bb[3],bb[4])
to the code above yields which is better, but a) does not respect the specified zoom level, and b) has a lot of unwanted horizontal padding.
I presume that adding width and height arguments to the leaflet() call would help but I am unsure how to automatically obtain the correct values. Also the resulting image would be very large necessitating a reduction in resolution.
How can I export the region of the map containing Italy at a specified zoom level without additional padding?
I dont know that what you want is possible (zoom = 12 and all of italy)...the two things seem mutually exclusive to me... unless you have a enormous figure... as you suggested.
I dont know for certain, but maybe the answer to your padding question is in the vwidth option of webshot. I suppose your figure needs to be taller than wide, so vwidth < vheight...
mapshot(m, file = "italy.png", vwidth = 700, vheight = 744)

Plotting regions and adding color in leaflet R

I need to plot a map of Denmark divided into regions (there are 5: Region Nordjylland, Midtjylland, Sydjylland, Sjælland and Hovedstaden) and then color the regions such that the different regions stand out clearly. I have to use leaflet, since it has other features, that I will use later. I found a map on naturalearthdata.com, that I think I can use, but I can't figure out how to color (or even indicate) the regions. The code I tried is below
library(rgdal)
library(leaflet)
download.file(file.path('http://www.naturalearthdata.com/http/',
'www.naturalearthdata.com/download/50m/cultural',
'ne_50m_admin_1_states_provinces_lakes.zip'),
f <- tempfile())
unzip(f, exdir=tempdir())
world <- readOGR(tempdir(), 'ne_50m_admin_1_states_provinces_lakes', encoding='UTF-8')
DK <- subset(world, name=="Denmark")
leaflet() %>% addTiles() %>% addTopoJSON(DK, weight = 1, color = "#444444", fill = TRUE)
How does one use the naturalearthdata.com data to plot regions/states/provinces of different countries? I have seen a very nice example at
http://www.56n.dk/kort/dk2050kort_age.html
but there is no sample code available.
I have also found a very nice example here: https://rpubs.com/walkerke/leaflet_choropleth - but I need a map of Denmark.
UPDATE: I have found a shapefile at http://www.kortforsyningen.dk which does the trick. So now my question is how do I combine my own data with a shapefile and plot it in leaflet? If I just put
DK <- readOGR(".../shape", layer="REGION")
leaflet(data=DK)
I get a blank screen...

R Leaflet doesn't add all markers

I'm trying to follow the example in the link below to create a map with all the markers
Tutorial: How to put dots on a Leaflet map with R
The source file is below
https://www.dropbox.com/s/az1yolknqwoxhb4/test_file.csv?dl=0
And the code that I tried
library(dplyr)
library(leaflet)
test_map <- read.csv("test_file.csv", header = TRUE, stringsAsFactors = FALSE)
m <- leaflet(test_map) %>% addTiles('http://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png',
attribution='Map tiles by Stamen Design, CC BY 3.0 — Map data © OpenStreetMap')
m %>% setView()
m %>% addCircles(~long, ~lat,
popup=test_map$index,
weight = 3,
color="#ffa500", stroke = TRUE, fillOpacity = 0.8)
I was able to create the map
However, the map only shows a fraction of points, since the data I have has locations all over Canada. When I tried to sub-select a city say like Toronto then some of the missing points shows up.
I'm not sure if i'm doing anything wrong or if this is a bug.I wonder if there's anyway for me to fix this problem or is there an alternative way to achieve a similar map?
Thank you :)
There are NA values in test_map variable.
add
test_map <- na.omit(test_map)
after reading csv.
By this method i have more markers than your image.

NASA tiles with leaflet in R

I would like to ask some help with regard to the leaflet package. When you draw an interactive map, you can do something like this.
library(leaflet)
library(magrittr)
m <- leaflet() %>%
setView(lng = -71.0589, lat = 42.3601, zoom = 8) %>%
addTiles()
m
If you want to add a third-party tile, you can do that too. The following link offers options for third-party tiles (http://leaflet-extras.github.io/leaflet-providers/preview/index.html) The following image is created with OpenWeatherMap.Precipitation.
### They work
m %>% addProviderTiles("MtbMap")
m %>% addProviderTiles("HikeBike.HikeBike")
m %>% addProviderTiles("OpenWeatherMap.Precipitation")
Some of the tile options in the link include tiles by NASA. I wanted to use one of them. So I tried the following codes. None of them unfortunately worked.
### The default map appears, then a black layer appears on top of the default layer.
m %>% addProviderTiles("NASAGIBS.ModisTerraTRUEColorCR")
m %>% addProviderTiles("NASAGIBS.ModisTerraBands367CR")
The only option which is working is the following.
m %>% addProviderTiles("NASAGIBS.ViirsEarthAtNight2012")
My next attempt was to use custom URL template with addTiles(). The URL is from the link above. But, this was not successful either; no error message appeared, but no change in tile.
m %>%addTiles(urlTemplate = "http://map1.vis.earthdata.nasa.gov/wmts-webmerc/MODIS_Terra_CorrectedReflectance_Bands367/default/{time}/{tilematrixset}{maxZoom}/{z}/{y}/{x}.{format}",
tileOptions(minZoom = 1, maxZoom = 8))
My final attempt was the following. This showed the default map, but an additional tile did not appear either.
leaflet() %>%
addTiles() %>%
setView(lng = -71.0589, lat = 42.3601, zoom = 8) %>%
addTiles(urlTemplate = "http://map1.vis.earthdata.nasa.gov/wmts-webmerc/MODIS_Terra_CorrectedReflectance_Bands367/default/{time}/{tilematrixset}{maxZoom}/{z}/{y}/{x}.{format}",
tileOptions(minZoom = 1, maxZoom = 8))
My question is whether this is a potential bug specifically with NASA tiles. Alternatively, what revision do I need in these scripts? Thank you for your help in advance.
UPDATE
I found a website which uses same NASA tiles. I specified NASAGIBS.ModisTerraTRUEColorCR and got the following image. The image is showing how a mail traveled from the US to Sweden. As you see, there is no image for both US and Europe. I think this could be the reason why I saw a black tile. I would like to know if anybody knows some details of NASA tiles. I chose the area which I can see the NASA image. But, I had no luck.
### I expected to see Japan area this time.
foo <- leaflet() %>%
setView(lng = 137.37, lat = 35.93, zoom = 5) %>%
addTiles()
foo %>% addProviderTiles("NASAGIBS.ModisTerraTRUEColorCR")
UPDATE 2
Today, I gave one more shot. At this moment, I managed to get the following image. I zoomed out a bit when I captured it. In UPDATE, I provided a map which you cannot see the US and Europe. In the new image, you see West coast of the States is in black. Given all observations, it seems to me that one may not get NASA images of a location all the time. Depending on when you ask NASA tiles, you may/may not have an image you want.
m <- leaflet() %>%
setView(lng = -71.0589, lat = 42.3601, zoom = 8) %>%
addTiles()
m %>% addProviderTiles("NASAGIBS.ModisTerraBands367CR")
Your final conclusion is correct: depending on what location you request imagery for and on the time of the request, the satellite may or may not yet have acquired the image. So you may get an actual image or just an empty one. (This is also stated in the GIBS API documentation.)
However, you can specify what day to request the image for via the 'time' option for addProviderTiles(). By specifying a date in the near past, you can get non-empty images for all locations if that is what you prefer.
This is the syntax:
> library(leaflet)
> library(magrittr)
> m <- leaflet() %>%
setView(lng = 4.5, lat = 51, zoom = 1) %>%
addTiles() %>%
addProviderTiles("NASAGIBS.ModisTerraTrueColorCR",
options = providerTileOptions(time = "2015-08-31", opacity = 0.5))
> m
At the time of writing (2015-08-31) I get this result:
It's cloudy in England, who would have guessed?
Most data happens to be there already, but there is no imagery for Alaska yet. If on the other hand, I specify yesterday's date
options = providerTileOptions(time = "2015-08-30", opacity = 0.5)
we get the full image:
Finally, the reason why
m %>% addProviderTiles("NASAGIBS.ModisTerraTRUEColorCR")
didn't work was probably because of a typo. It should be
m %>% addProviderTiles("NASAGIBS.ModisTerraTrueColorCR")

Resources