# 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`
This very generalised repex assumes you want your background map to be:
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