rstudio / leaflet

R Interface to Leaflet Maps
http://rstudio.github.io/leaflet/
Other
805 stars 508 forks source link

image not found when using addControl( html = "<img src =' source'>" #674

Closed SL-itw closed 4 years ago

SL-itw commented 4 years ago

When I inspect the image file it says the image is not found. However ever when I check the folder the image is there and shows when I preview it. The code is rather long so here are screen shots of where I am having the problem. The code below includes the data used for the screen shots

Screen Shot 2020-04-10 at 3 34 27 PM Screen Shot 2020-04-10 at 3 08 21 PM Screen Shot 2020-04-10 at 3 35 56 PM Screen Shot 2020-04-10 at 3 11 19 PM
library(tidyverse)
library(tigris) 
library(leaflet)
library(tidycensus)
library(dplyr)
library(magrittr)
library(sf)
library(ggplot2)
library(leaflet)
library(leaflet.extras)
library(htmlwidgets)
library(htmltools)

###########
### DATA ###
###########

###################### census data with Covid-19 data
census_data <- read_csv(https://raw.githubusercontent.com/sl4269/Covid-19-Spatial-Analysis/master/Covid-19_NYC/covid_census.csv)

####################### NYC zipcodes
zips <- read_csv(https://raw.githubusercontent.com/sl4269/Covid-19-Spatial-Analysis/master/Covid-19_NYC/NYCzips.csv)

#################### NYCshapeFile 
nycshape <- zctas(cb = T, starts_with = c(zips$zips))

################## merging shapefile with data
zipsmap <- geo_join(nycshape, 
                        covCen, 
                        by_sp = "GEOID10", 
                        by_df = "GEOID",
                        how = "inner")

##############
## Leaflet plot ###
##############

######## palettes and labels, and legend creation
nhBLack<- covCen %>% 
  pull(nhblack_pct)

# get values for lower & upper "Pew breaks"
nhBLack_lower <- ((2/3) * nhBLack)
nhBLack_upper <- (2 * nhBLack)

pal_BLack <- colorBin(
  palette = c("#EDEDED", "#FF94C0", "#FF2C54"),
  domain = zipsmap$nhblack_pct,
  bins = c(0, nhBLack_lower, nhBLack_upper, max(zipsmap$nhblack_pct, na.rm = T))
)

nhHisp<- covCen %>% 
  pull(hispanic_pct)

# get values for lower & upper "Pew breaks"
nhHisp_lower <- ((2/3) * nhHisp)
nhHisp_upper <- (2 * nhHisp)

pal_Hisp <- colorBin(
  palette = c("#EDEDED", "#FF94C0", "#FF2C54"),
  domain = zipsmap$hispanic_pct,
  bins = c(0, nhHisp_lower, nhHisp_upper, max(zipsmap$hispanic_pct, na.rm = T))
)

pal_rate <- colorQuantile(
  palette = c("#EDEDED", "#94C6E7", "#4CB1DF"),
  domain = zipsmap$case_rate,
  probs = seq(0, 1, length.out = 4)
)

labels <- 
  paste0(
    "Zip Code: ",
    zipsmap@data$GEOID10, "<br/>",
    "% Non Hispanic Black: ",
    zipsmap@data$nhblack_pct, "<br/>",
    "% Hispanic: ",
    zipsmap@data$hispanic_pct, "<br/>",
    "Case rate: ",
    zipsmap@data$case_rate) %>%
  lapply(htmltools::HTML)

labs <- lapply(seq(nrow(zipsmap)), function(i) {
  paste0(
    "Non Hispanic Black: %", 
    round(zipsmap@data[i, "nhblack_pct"], 0), "<br>",
    "Hispanic: %", 
    round(zipsmap@data[i, "hispanic_pct"], 0), "<br>",
    "Case rate: ", round(zipsmap@data[i, "case_rate"], 3)
  ) 
})

legend_scale <- data.frame(
  race_ethnicity = c(rep(1, 3), rep(2, 3), rep(3, 3)),
  case_rate = c(rep(seq(1, 3, 1), 3)),
  color = c("#F1F1F1", "#C3DEEE", "#A1D3EA",
            "#F7DBE7", "#CAC8E3", "#A6BDDF",
            "#F7C1CB", "#CAAEC8", "#A6A3C4")
)
# legend
legend <- ggplot() + 
  geom_tile(
    data = legend_scale,
    aes(x = race_ethnicity, y = case_rate, fill = color)
  ) + 
  scale_fill_identity() +
  labs(x = "race/ethnicity →",
       y = "Case Rate →") +
  theme(
    axis.title = element_text(size = 20),
    axis.line = element_blank(),
    axis.text = element_blank(),
    axis.ticks = element_blank(),
    panel.grid = element_blank(),
    panel.background = element_blank(),
    plot.margin = margin(10, 10, 10, 10),
    plot.background = element_rect(fill = "transparent", color = NA)
  )

#install.packages("svglite")
library(svglite)

# save SVG legend
ggsave("Covid-19_NYC/img/zipsmap_race_caserate.png", plot = legend,
       width = 3, height = 3, bg = "transparent")

################# map

zipsmap %>% 
  leaflet(
   width = "100%",
    options = leafletOptions(zoomSnap = 0.25, zoomDelta = 0.5)
 ) %>% 
  # add base map
  addProviderTiles("CartoDB") %>% 
  # add zip codes
  addPolygons(group = "Black Race",
              fillColor = ~pal_BLack(x = race_nhBlack),
              fillOpacity = 0.5,
              stroke = F,
              smoothFactor = 0.2) %>%
  addPolygons(group = "Hisp Race",
              fillColor = ~pal_Hisp(x = race_hisp),
              fillOpacity = 0.5,
              stroke = F,
              smoothFactor = 0.2) %>%
  addPolygons(group = "Case Rate",
              fillColor = ~pal_rate(case_rate),
              fillOpacity = 0.5,
              stroke = F,
              smoothFactor = 0.2) %>% 

  addLayersControl(
    baseGroups = c("Black Race", "Hisp Race"),
    options = layersControlOptions(collapsed = FALSE),
    position = "topright"
  ) %>% 

  htmlwidgets::onRender("
    function(el, x) {
      this.on('baselayerchange', function(e) {
        e.layer.bringToBack();
      })

    }

  "
  ) %>% 

  addPolygons(
    label = lapply(labs, htmltools::HTML),
    labelOptions = labelOptions(textsize = "12px"),
    fillColor = NA,
    fillOpacity = 0,
    color = "gray",
    weight = 1,
    opacity = 1,
    highlightOptions = highlightOptions(weight = 2)) %>% 

  addResetMapButton() %>% 

  addFullscreenControl() %>% 

  suspendScroll(sleepNote = F, sleepOpacity = 1) %>% 

  addControl(
    html = "<img src = '/Users/stevenlawrence/Desktop/cumc_github/Covid-19/Covid-19_NYC/img/zipsmap_race_caserate.png', width = '100', height = '100'>",
    position = "topright",
    className = "legend-bivar"
  )
schloerke commented 4 years ago

Need to use a file protocol within browsers to access a local file.

file:///Users/stevenlawrence/Desktop/cumc_github/Covid-19/Covid-19_NYC/img/zipsmap_race_caserate.png

(Would be better if the path was a relative path. But this may not be possible until hosted by shiny.)

SL-itw commented 4 years ago

Thank you for the quick reply.

I agree!

This has solved by initial problem but now I am getting this error which is great because at least its seeing the file. So now I need to some how allow my browser to allow this.

Screen Shot 2020-04-10 at 5 14 19 PM
schloerke commented 4 years ago

Ah, you already have it as a shiny application.

Use a relative path and put the image in the www of your Shiny application directory. That will be the only way you can load file path like a relative image path.

Folder structure

app.R
www
  |- img
    |- zipsmap_race_caserate.png

Leaflet code

#...
addControl(
    html = "<img src = 'img/zipsmap_race_caserate.png', width = '100', height = '100'>",
    position = "topright",
    className = "legend-bivar"
  )
SL-itw commented 4 years ago

Thank you! The problem has been solved. I should also include that it terns out that R also stops one from accessing files in this particular way so I had to upload my image to a website I am hosting on github and then copy the image address from the page its on then it worked completely.

leaflet code


#... 
addControl(
           html = "<img src = 'https://sl4269.github.io/zipsmap_race_caserate.svg' width = '128' height = '128'>",
          position = "topright",
          className = "legend-bivar"
        )

I am not sure why but now I know that having an image already hosted on another site somehow helps shiny recognize it because R won't let you access it locally for some reason.

Screen Shot 2020-04-10 at 10 53 49 PM

A big thank you!

zyllifeworld commented 2 years ago

I think the addResourcePath() function from shiny can help ,if you want insert a image from you local path, just add this line command:

addResourcePath('image','../images/')

then you can just give the image url as "image/blablaXXXX" when you deploy you shiny app.

if you use golem, you can also use this command: golem::add_resource_path('image','../images/')