NASA tiles with leaflet in R - 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")

Related

r leaflet limit max zoom with markerClusterOptions turned on

I have a leaflet map, which has points that overlap when zoomed out. I have therefore used markerClusterOtions() so that as the user zooms in, the overlapping points that were grouped into clusters will separate.
This is all working fine, but my problem is that I would like to apply a zoom limit. I don't want the users to be able to zoom right in to street level, because then they could see the exact address of my markers (which in this case would be a data protection issue). I want the markers to freeze when the user reaches the max zoom limit, but until then, they should keep separating out as the user zooms in.
I thought this could be achieved by setting the maxZoom in tileOptions, and freezeAtZoom in markerClusterOptions, but it doesn't work and I keep getting a strange error.
Here is my code:
# Create the interactive map:
myleaflet <- leaflet() %>%
# Add open street map (default base layer)
addTiles(tileOptions(minZoom = 1, maxZoom = 12)) %>%
# Add transformed shapefile of regions
addPolygons(data = regions, weight = 5, col = "black") %>%
# Add markers for case residence with descriptive labels:
addMarkers(lng = mydata$home_long,
lat = mydata$home_lat,
popup = paste("ID: ", mydata$id, "<br/>",
"Link: ", mydata$links, "<br/>",
"Clade: ", mydata$wgs_cluster),
clusterOptions = markerClusterOptions(freezeAtZoom = "max"))
# View the map:
myleaflet
And here is the error I get (it appears when I try to view the map, not when running the code to create it):
Error in dirname(to) : path too long
If I remove the zoom options, I can view the map, but then the zoom is not limited.
I have looked at posts regarding this error, and I can see that it is associated with Windows OS and paths that are too long. I am using windows, and this is part of an R markdown chunk, but the chunk name is 24 characters (so within the limit) and the R markdown file name is short - also, the error only occurs when I run the above code, which is just part of the code in that chunk. I can't see how adding the zoom options makes something too long, since they are supposed to be valid arguments?
Any insights as to what I'm doing wrong would be much appreciated.
Update:
It seems my mistake was not specifying the argument name for tileOptions - also freezeAtZoom is not necessary to specify when the maximum zoom limit is already specified for the map tiles (in fact if both are specified, the unclustered markers also show up on the map).
The code below works:
# Create the interactive map:
myleaflet <- leaflet() %>%
# Add open street map (default base layer)
addTiles(options = tileOptions(maxZoom = 12)) %>%
# Add transformed shapefile of regions
addPolygons(data = regions, weight = 5, col = "black") %>%
# Add markers for case residence with descriptive labels:
addMarkers(lng = mydata$home_long,
lat = mydata$home_lat,
popup = paste("ID: ", mydata$id, "<br/>",
"Link: ", mydata$links, "<br/>",
"Clade: ", mydata$wgs_cluster),
clusterOptions = markerClusterOptions())
# View the map:
myleaflet
Since the first option in addTiles() is map I suppose that it was previously interpreting the tileOptions argument as a file path to a map, but I would be interested to know if there are other interpretations, since the traceback showed the problem with the file path length was in saving to html, not importing / reading a file.

When using Leaflet for R, how can I change font size of the OpenStreetMap basemap?

I am creating maps for offline use using Leaflet for R and OpenStreetMap, adding information such as points of interest, and saving them as png files. This works well, but I would like to be able to adjust the font size on the OpenStreetMap basemap layer. EDIT This is because for very large maps (one I am working on is 4,500 pixels square) the text is so small as to be unreadable, even though the road network is visible. For example, this code:
require(leaflet)
require(mapview)
require(webshot)
m <- leaflet() %>%
setView(lng = -0.134509, lat = 51.509898, zoom = 17) %>%
addTiles(group = "OpenStreetMap")
mapshot(m, file = file.path("c:\\Temp\\stack1.png"), vwidth = 500, vheight = 500)
produces this output:
In this image, I want to be able to change (say) the size of the font used to display "Jermyn Street". I have experimented with zoomOffset and tileSize, like this:
m <- leaflet() %>%
setView(lng = -0.134509, lat = 51.509898, zoom = 17) %>%
addTiles(group = "OpenStreetMap",
tileOptions(tileSize = 512,
zoomOffset = -1))
So far, all combinations I have tried result in blank output, like the image below.
Is it even possible to change the basemap font on such tiles?
(I would be open to using a different tile provider, if that helped.)
Not by passing arguments to a tile server you can’t. You’ll have to run your own tile server configured with larger text size or look for a map style/theme with larger text size.
You can refer to https://help.openstreetmap.org/questions/29621/how-to-increase-font-size-when-viewing-osm

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

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.

How to retrieve WMS image from certain time/date

I'm trying to get de precipation radar data from the KNMI loaded in a leaflet in R. The data is located here: http://adaguc.knmi.nl/contents/webservices/WebServices_RADNL_OPER_R___25PCPRR_L3.html
So far, I've managed to get the current radar image to a leaflet layer with the following code:
require("leaflet")
require("dplyr")
leaflet() %>% addTiles() %>%
addWMSTiles(
"http://geoservices.knmi.nl/cgi-bin/RADNL_OPER_R___25PCPRR_L3.cgi",
layers = "RADNL_OPER_R___25PCPRR_L3_KNMI",
options = WMSTileOptions(format = "image/png", transparent = TRUE),
attribution = "KNMI"
)
So far so good...
But what I really would like, is to get a radar image from a given timestamp. The series goes back to 2009 (see example from the KNMI viewer here: http://geoservices.knmi.nl/viewer2.0/?srs=EPSG%3A3857&bbox=-725.7203842048766,6500000,1220725.7203842048,7200000&service=http%3A%2F%2Fgeoservices.knmi.nl%2Fcgi-bin%2FRADNL_OPER_R___25PCPRR_L3.cgi%3F&layer=RADNL_OPER_R___25PCPRR_L3_COLOR%24image%2Fpng%24true%24default%241%240&selected=0&dims=time$current&baselayers=streetmap$world_line ).
On the web, I have found several examples of leaflet that supports dates/times, (like this: http://apps.socib.es/Leaflet.TimeDimension/examples/example14.html), but unfortunalety I lack the skills to convert this example to the R-version of leaflet.
Can this be done? Can I, for example, retrieve the precipation radar image from 2017-01-07T04:00? If yes: where would/could I start?
Or if it cannot be done with leaflet; any other suggestions?
That was easier than expected ;-)
I just had to add a TIME-variable in the WMSTileOptions.
This works:
require("leaflet")
require("dplyr")
leaflet() %>% addTiles() %>%
addWMSTiles(
"http://geoservices.knmi.nl/cgi-bin/RADNL_OPER_R___25PCPRR_L3.cgi",
layers = "RADNL_OPER_R___25PCPRR_L3_COLOR",
options = WMSTileOptions(format = "image/png", transparent = TRUE, TIME = "2017-01-07T04:00:00"),
attribution = "KNMI neerslagradar"
)

How to use WMS in R?

I like to implement a special WMS-layer with leaflet() in R. But I have no success with the WMS-layer I like to use.
library("leaflet")
library("sp")
# this example from the tutorial works
leaflet() %>% addTiles() %>% setView(-93.65, 42.028, zoom = 4) %>%
addWMSTiles(
"http://mesonet.agron.iastate.edu/cgi-bin/wms/nexrad/n0r.cgi",
layers = "nexrad-n0r",
options = WMSTileOptions(format = "image/png", transparent = TRUE)
)
# but for my implementation it don't work
leaflet() %>% addTiles() %>% setView(lat = 53.8, lng = 12.6, zoom = 8) %>%
addWMSTiles("http://www.umweltkarten.mv-regierung.de/script/mv_a3_wasserschutz_wms.php?",
layers = "t2_bib_p",
options = WMSTileOptions(format = "image/png")
)
I assume that there is a problem with the Coordinate Refernce System. Because the WMS-layer I like to use, have not a standard CRS. So I try to expermented with this WMSTileOptions():
crs=CRS("+init=epsg:5650")
The idea is to use WMS-Layers as background images for my vector data. The vector data come mainly from shape-files and GPS-data (text files). The purpose is to create maps which i can use in a report.
If you know other possibles beside leaflet to use WMS in R there are also welcome?
I notice that if you investigate that base URL it says
msWMSDispatch(): WMS server error. Incomplete WMS request: VERSION
parameter missing
and by researching the website I determined that the proper format is:
https://www.umweltkarten.mv-regierung.de/script/mv_a3_wasserschutz_wms.php?SERVICE=WMS&REQUEST=GetCapabilities&VERSION=1.3.0
which yields quite a lot of WMS data if you put it in your browser.
We can use "find" to see which layers are available to be queried. There are several, such as t3_ksg, t3_wsg, and lungwms, but it seems that t2_bib_p is not available for mv_a3_wasserschutz_wms.

Resources