saving R leaflet map as html: Raster not shown in Firefox/ Safari but in Chrome
Unfortunately, I struggle to show a reproducible example here. The issue occurs only, when I add a locally saved raster file (140mb) to a leaflet map. And I don't know how to share such a large file here. The map shows fine in the rStudio viewer and in Chrome. But it fails to show the raster in Firefox and Safari (Firefox on OSX and iOS). Even auto zoom and pan does not work.
When I add a system raster file, everything works as expected:
library(leaflet)
library(leafem)
library(raster)
library(stars) #to access the stars system.file
tif = system.file("tif/L7_ETMs.tif", package = "stars")
x2 <- raster(tif)
map_raster <- leaflet() %>%
addTiles() %>%
leafem:::addGeoRaster(
x2,
opacity = 1,
colorOptions = colorOptions(
palette = grey.colors(256)
)
)
library(htmlwidgets)
saveWidget(map_raster, file = "TestExport_raster.html", selfcontained = T)
But when I replace x2 with the local raster, it does not work. Tried adding an object from the raster
and the stars
package, but with no difference.
Any help on that? Is the raster just too big for a leaflet-map?
The question might be related to this one: saving R leaflet map as html: tiles not included
Best, Beni
do you know?
how many words do you know
See also questions close to this topic
-
pivot_wider does not keep all the variables
I would like to keep the variable
cat
(category) in the output of my function. However, I am not able to keep it. The idea is to apply a similar function tom <- 1 - (1 - se * p2)^df$n
based on the category. But in order to perform that step, I need to keep the variable category.Here's the code:
#script3 suppressPackageStartupMessages({ library(mc2d) library(tidyverse) }) sim_one <- function() { df<-data.frame(id=c(1:30),cat=c(rep("a",12),rep("b",18)),month=c(1:6,1,6,4,1,5,2,3,2,5,4,6,3:6,4:6,1:5,5),n=rpois(30,5)) nr <- nrow(df) df$n[df$n == "0"] <- 3 se <- rbeta(nr, 96, 6) epi.a <- rpert(nr, min = 1.5, mode = 2, max = 3) p <- 0.2 p2 <- epi.a*p m <- 1 - (1 - se * p2)^df$n results <- data.frame(month = df$month, m, df$cat) results %>% arrange(month) %>% group_by(month) %>% mutate(n = row_number(), .groups = "drop") %>% pivot_wider( id_cols = n, names_from = month, names_glue = "m_{.name}", values_from =m ) } set.seed(99) iters <- 1000 sim_list <- replicate(iters, sim_one(), simplify = FALSE) sim_list[[1]] #> # A tibble: 7 x 7 #> n m_1 m_2 m_3 m_4 m_5 m_6 #> <int> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> #> 1 1 0.970 0.623 0.905 0.998 0.929 0.980 #> 2 2 0.912 0.892 0.736 0.830 0.890 0.862 #> 3 3 0.795 0.932 0.553 0.958 0.931 0.798 #> 4 4 0.950 0.892 0.732 0.649 0.777 0.743 #> 5 5 NA NA NA 0.657 0.980 0.945 #> 6 6 NA NA NA 0.976 0.836 NA #> 7 7 NA NA NA NA 0.740 NA
Created on 2022-05-07 by the reprex package (v2.0.1)
-
calculate weighted average over several columns with NA
I have a data frame like this one:
ID duration1 duration2 total_duration quantity1 quantity2 1 5 2 7 3 1 2 NA 4 4 3 4 3 5 NA 5 2 NA
I would like to do a weighted mean for each subject like this:
df$weighted_mean<- ((df$duration1*df$quantity1) + (df$duration2*df$quantity2) ) / (df$total_duration)
But as I have NA, this command does not work and it is not very nice....
The result would be this:
ID duration1 duration2 total_duration quantity1 quantity2 weighted_mean 1 5 2 7 3 1 2.43 2 NA 4 4 3 4 4 3 5 NA 5 2 NA 2
Thanks in advance for the help
-
I am to extract data from netCDF file using R for specific loaction the code i've written as showen and I have an error at the end of the code
I need some help with extracting date from NetCDF files using R , I downloaded them from cordex (The Coordinated Regional climate Downscaling Experiment). In total I have some files. This files have dimensions of (longitude, latitude, time) and the variable is maximum temperature (tasmax). At specific location, I need to extract data of tasmax at different time. In total I have some files. This files have dimensions of (longitude, latitude, time) and variable maximum temperature (tasmax). At specific location, I need to extract data of tasmax at different time.I wrote the code using R but at the end of code, an error appeared. Error ( location subscript out of bounds)
getwd() setwd("C:/Users/20120/climate change/rcp4.5/tasmax")
dir() library ("ncdf4") libra,-ry(ncdf4.helpers) library ("chron") ncin <- nc_open("tasmax_AFR-44_ICHEC-EC-EARTH_rcp45_r1i1p1_KNMI-RACMO22T_v1_mon_200601-201012.nc") lat <- ncvar_get(ncin, "lat") lon <- ncvar_get(ncin, "lon") tori <- ncvar_get(ncin, "time") title <- ncatt_get(ncin,0,"title") institution <- ncatt_get(ncin,0,"institution") datasource <- ncatt_get(ncin,0,"source") references <- ncatt_get(ncin,0,"references") history <- ncatt_get(ncin,0,"history") Conventions <- ncatt_get(ncin,0,"Conventions") tustr <- strsplit(tunits$value,"") ncin$dim$time$units ncin$dim$time$calendar tas_time <- nc.get.time.series(ncin, v = "tasmax", time.dim.name = "time") tas_time[c(1:3, length(tas_time) - 2:0)] tmp.array <- ncvar_get(ncin,"tasmax") dunits <- ncatt_get(ncin,"tasmax","units") tmp.array <- tmp.array-273.15 tunits <- ncatt_get(ncin,"time","units") nc_close(ncin) which.min(abs(lat-28.9)) which.min(abs(lon-30.2)) tmp.slice <- tmp.array[126,32981,] tmp.slice
Error in tmp.array[126, 32981, ] : subscript out of bounds
-
Display a projected raster on a projected basemap in R/leaflet?
Is it possible to display a projected raster on a projected basemap in R/leaflet? The
addRasterImage()
functions says that the projection needs to be in EPSG:3857. Can this not be changed by settingproject = false
? I am able to display projected vector data on a projected basemap, but not raster ...My attempt:
library(leaflet) library(raster) library(sf) # Find location in northern Canada ca_df <- data.frame(long = -114.3717401, lat = 62.4525548, name="Yellowknife", stringsAsFactors = F ) ca_pt <- st_as_sf(ca_df,coords = c("long", "lat"), crs = 4326) # Project to Alaska Polar Stereographic ca_pt_5936 <- as_Spatial(st_transform(ca_pt, 5936))@coords # Create raster around point r_5936 <- raster( matrix(round(runif(100)), ncol = 10), xmn = ca_pt_5936[[1]] - 50000, xmx = ca_pt_5936[[1]] + 50000, ymn = ca_pt_5936[[2]] - 50000, ymx = ca_pt_5936[[2]] + 50000, crs = "EPSG:5936" ) # Project raster to Web Mercator (needed to get the extent in lat/long) r_3857 <- projectRaster(r_5936, crs="EPSG:3857", method = "ngb") # Prep for leaflet: https://github.com/rstudio/leaflet/issues/550 tile_url <- 'https://services.arcgisonline.com/arcgis/rest/services/Polar/Arctic_Ocean_Base/MapServer/tile/{z}/{y}/{x}.png' origin <- c(-2.8567784109255e+07, 3.2567784109255e+07) resolutions <- c( 238810.813354,119405.406677, 59702.7033384999, 29851.3516692501,14925.675834625, 7462.83791731252,3731.41895865639, 1865.70947932806,932.854739664032, 466.427369832148, 233.213684916074, 116.60684245803701, 58.30342122888621, 29.151710614575396, 14.5758553072877, 7.28792765351156, 3.64396382688807, 1.82198191331174, 0.910990956788164, 0.45549547826179, 0.227747739130895, 0.113873869697739, 0.05693693484887, 0.028468467424435) epsg5936 <- leafletCRS( crsClass = 'L.Proj.CRS', code = 'EPSG:5936', proj4def = '+proj=stere +lat_0=90 +lat_ts=90 +lon_0=-150 +k=0.994 +x_0=2000000 +y_0=2000000 +datum=WGS84 +units=m +no_defs', origin = origin, resolutions = resolutions ) # Map leaflet(r_3857, options= leafletOptions( crs=epsg5936)) %>% addTiles(urlTemplate = tile_url, attribution = "Esri, DeLorme, GEBCO, NOAA NGDC, and other contributors", options = tileOptions(minZoom = 0, maxZoom = 4)) %>% addRasterImage(r_5936, project = F)
The output doesn't display the raster.
-
Javascript: Correct syntax for making editable custom properties (on click, toggle colour of Leaflet GeoJSON object)
I've written the following javascript code using leaflet to make multiple red polylines with each having property called "active" which starts as true.
for (let i = 0; i < railLinks.length; i++) { var polyline = new L.geoJSON(railLinks[i].polyline, { linkNumber: railLinks[i].linkNumber, active: true, //THIS LINE DOESNT DO WHAT I THOUGHT IT WOULD style: function(active) { return { weight: 2, color: 'red' }; } }).addTo(map); polyline.on('click', function() { set = !this.active this.active = set; this.setStyle({ color: getColor(set) }); }); } function getColor(x) { return x ? 'black': '#888888'; };
I'm tring to implement a toggle so that when you click a true polyline it turns to false and vice versa.
With this I would expect the first click to make grey ("false"), then black, then grey etc. Instead the first click makes black (representing true), suggesting the initial state was not true.
I would imagine the problem is with my syntax and that
active: true
is not the same property being changed as the later
this.active
as I can set the first active to any value without affecting the on click behaviour. Any ideas what this should be?
-
Next.js dynamic import with server-side-rendering turned off not working on production build
I'm currently building a site using the leaflet package. This package however needs the window object. That's why I'm importing a component made with leaflet as a dynamic component with ssr turned off. Just like this:
import dynamic from "next/dynamic"; const MapWithNoSSR = dynamic(() => import("../../map"), { ssr: false }); export default function faqOnly(props){ ... return (<> <MapWithNoSSR /></>) }
Map component looks like this:
import React, { useEffect, useState, useRef } from "react"; import { OpenStreetMapProvider } from 'leaflet-geosearch'; import "leaflet/dist/leaflet.css"; import 'leaflet/dist/leaflet.css' import 'leaflet-defaulticon-compatibility/dist/leaflet-defaulticon-compatibility.css' import "leaflet-defaulticon-compatibility"; import dynamic from "next/dynamic"; const L = dynamic(() => import("leaflet"), { ssr: false, suspense: true, loading: () => <p>...</p> }); function Map(props) { useEffect(async () => { if(window === undefined) return const provider = new OpenStreetMapProvider(); const results = await provider.search({ query: props.adress }); if(results.length > 0 == true){ var map = L.map('map', { center: [results[0].y, results[0].x], zoom: 18, layers: [ L.tileLayer('https://tiles.stadiamaps.com/tiles/alidade_smooth_dark/{z}/{x}/{y}{r}.png', { attribution: '' }), ] }) L.marker([results[0].y, results[0].x]).addTo(map) }else{ document.getElementById("map").style.display = "none" } }, []) return <div id="map" style={{ height: "30vh"}}></div> } export default Map;
And I get this error when I run
npm run build
:ReferenceError: window is not defined at E:\Github\Planer\rl-planer\node_modules\leaflet\dist\leaflet-src.js:230:19 at E:\Github\Planer\rl-planer\node_modules\leaflet\dist\leaflet-src.js:7:66 at Object.<anonymous> (E:\Github\Planer\rl-planer\node_modules\leaflet\dist\leaflet-src.js:10:3) at Module._compile (node:internal/modules/cjs/loader:1101:14) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10) at Module.load (node:internal/modules/cjs/loader:981:32) at Function.Module._load (node:internal/modules/cjs/loader:822:12) at Module.require (node:internal/modules/cjs/loader:1005:19) at require (node:internal/modules/cjs/helpers:102:18) at Object.<anonymous> (E:\Github\Planer\rl-planer\node_modules\leaflet-geosearch\dist\geosearch.js:1:7) { type: 'ReferenceError' }
This works fine in development, but when I try to build the project (next build), it throws a "window is not defined" error inside the leaflet package, which it hasn't been doing before when I was working on it in development mode.
I looked through other questions here, but it seems like moving the dynamic import outside the component fixed it for everyone but me. Am I just stupid or what's the problem here?
-
Bind spatial data frames
I have a long panel dataset (Data_Base) with the name of the 32 states in Mexico through 28 years in time (928 obs). I have in another .rds file the spatial data for these 32 states (mex.sf), in total of 32 obs. I want to bind the dataset with the spatial data. Of course the spatial data from the file mex.sf should be repeated 28 times per state due the difference in longitude of observations. I try with the following command specifying the condition to merge per name of state:
example <- merge(Data_Base, mex.sf, by=intersect(Data_Base$State,mex.sf$NAME_1))
Nevetheless I ended up with the following error message:
Error in fix.by(by.x, x) : 'by' must specify uniquely valid columns
Bellow an example of how the data looks like
Does anyone knows why cannot bind them?
-
Setting colors by factor in country map in R (raster package)
I am trying to assign each region of Kenya a color according to the vector with colors I made. I have already made a vector with colors as elements and region names as names. I think I have already everything I need, but I simply don´t know how to assign those colors to the right region. I only used data from the raster package and a numerical vector called:
This is the data I´d like to use to color the map
library(raster) library("viridis") Kenya = getData("GADM", country = "Kenya", level = 1) Kenya@data Kpoly <- Kenya@polygons ggplot(fortify(Kenya), aes(long, lat, group = group, fill = id)) + geom_polygon() + theme_void() + coord_equal() + scale_fill_manual("Kenya - Z score by region", values = colors_map, labels = colfac2)
I already tried to play with the parameters, but I can´t quite get the result I want.