This very generalised repex assumes you want your background map to be:
- based on your example geo coordinates
- 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](https://cdn.statically.io/img/i.sstatic.net/FyCAnM9V.jpg)