rggplot2r-leaflet

How to draw a custom map in the style of NASAGIBS.ViirsEarthAtNight2012 using R


  1. "NASAGIBS.ViirsEarthAtNight2012" is an optional layer parameter under the addProviderTiles function in the leaflet and leafletCN packages.
  2. I really like the drawing effect of this map.
  3. How can I draw a map similar to this one, but with more customization options rather than just one layer?
  4. Here is the picNASAGIBS.ViirsEarthAtNight2012.
# Required packages
library(leaflet)  # Load the leaflet package for interactive maps
library(leaflet.extras)  # Load additional leaflet extras
library(leafletCN)  # Load leaflet for Chinese maps
# Generate data
geo = data.frame(long = rep(121.44, 1000),
                 lat = rep(31.22, 1000))  # Create a data frame with longitude and latitude

# Plot
map <- leaflet(geo) %>%  # Create a leaflet map with the geo data
  amap(group = "Gaode") %>%  # Add Gaode map as Layer 1
  addProviderTiles(providers$NASAGIBS.ViirsEarthAtNight2012, 
                   group = "DarkBackground")  # Add DarkBackground NASA map as Layer 2
map  # Display the map`

Solution

  • This very generalised repex assumes you want your background map to be:

    1. based on your example geo coordinates
    2. a continuous (raster) surface like your example map

    Your example geo df creates 1,000 identical points with no values to colour each cell, but I have used it as a basis to create a raster dataset. You will need to work out how to convert your geo df to a raster. Some options include terra::rasterize() and stars::st_rasterize(). Once you have converted your df to a raster, you can then use leaflet::addRasterImage() to plot your data.

    Loads require packages and create example data:

    library(terra)
    library(sf)
    library(dplyr)
    library(leaflet)
    library(leaflet.extras)
    library(leafletCN)
    library(ggplot2)
    
    # Create a spatraster based on your example coordinates
    set.seed(1)
    geo <- rast(nrow = 32, ncol = 32, nlyrs = 1,
                xmin = 120, xmax = 124, 
                ymin = 30, ymax = 34, 
                names = "colour_var",
                crs = "EPSG:4326") %>%
      init("cell")
    
    # Assign random values to geo
    geo[] <- sample(1:20, nrow(geo) * ncol(geo), replace = TRUE)
    

    Assign colour values to geo based on colour_var values:

    palcol <- colorNumeric(c("#020321", "#081138", "#c0965f" , "#faebb3", "#fef9d4"),
                           values(geo),
                           na.color = "transparent")
    

    Plot:

    map <- leaflet() %>%
      amap(group = "Gaode") %>% 
      addProviderTiles(providers$NASAGIBS.ViirsEarthAtNight2012, 
                       group = "DarkBackground") %>%
      addRasterImage(geo, colors = palcol, opacity = 1) 
      
    map
    

    result