r-spatial / leafem

leaflet extensions for mapview
https://r-spatial.github.io/leafem/
Other
108 stars 29 forks source link

Transparency not working with addGeotiff and colorOptions #54

Closed psolymos closed 2 years ago

psolymos commented 2 years ago

I am having issues with transparent colors for the NA values in the raster (GeoTIFF). I tried different values for na.color = "transparent" and all gave the same black result, using CRAN (v 0.1.6) and dev (SHA1 660d9886) being the same in this regard.

library(leaflet)
library(leafem)

leaflet() %>%
        addProviderTiles("Esri.WorldImagery") %>%
        addGeotiff(
          url = "https://peter.solymos.org/testapi/amro1k.tif",
          project = FALSE,
          opacity = 0.8,
          colorOptions = colorOptions(
             palette = hcl.colors(50, palette = "inferno"), 
             domain = c(0, 0.62),
             na.color = "transparent"))
Black background around raster
tim-salabim commented 2 years ago

This is a tricky one.

image

The georaster.noDataValue just doesn't quite match the current value being processed (vals), even though it should...

@DanielJDufour any ideas how to catch this? Is there an alternative to checking via vals === georaster.noDataValue (whoch is what I'm currently doing - https://github.com/r-spatial/leafem/blob/master/inst/htmlwidgets/lib/georaster-for-leaflet/georaster-binding.js#L108)?

tim-salabim commented 2 years ago

This seems to work:

vals.toExponential(7) === georaster.noDataValue.toExponential(7)

whereas a value of 8 returns false

tim-salabim commented 2 years ago

and it seems to fix the issue

image

psolymos commented 2 years ago

Making sure I understand: georaster.noDataValue is the value taken from the TIF, and it is not matching with what georaster expects (a numerical thing when evaluating?). Should noDataValue be set when saving the TIF?

tim-salabim commented 2 years ago

Yes, correct. Can you set the noDataValue when saving the .tif?

psolymos commented 2 years ago

raster::NAvalue() lets you to set the NA value in R, but that does not affect how the TIF gets written by raster::writeRaster(). The NA values is -Inf. If I set it to -9999, save, and read the file back in I still get -Inf which is what drives the numerical issue described above.

However, I can save it as a {stars} object with write_stars(st_as_stars(r), "amro1k-stars.tif") and that solves this issue:

leaflet() %>%
        addProviderTiles("Esri.WorldImagery") %>%
        addGeotiff(
          url = "https://peter.solymos.org/testapi/amro1k-stars.tif",
          project = FALSE,
          opacity = 0.8,
          colorOptions = colorOptions(
             palette = hcl.colors(50, palette = "inferno"), 
             domain = c(0, 0.62),
             na.color = "transparent"))
Fixed

Thanks for the help!