walkerke / mapgl

R interface to Mapbox GL JS v3 and Maplibre GL JS
https://walker-data.com/mapgl
Other
91 stars 5 forks source link

Using local png files as icons #22

Closed enriquevaa closed 1 month ago

enriquevaa commented 4 months ago

Hi Kyle, I have read your reference and am looking for a way to use an image from an external URL to visualize a point feature on the map. Is it possible this? Here is an example of what I am looking for: https://docs.mapbox.com/mapbox-gl-js/example/add-image/ Cheers

walkerke commented 4 months ago

I don't currently have that enabled, but I think it should be do-able!

ews-grmunjal commented 4 months ago

@enriquevaa not exactly the same but you could try creating your own style in mapbox and add your icons to the spritesheet through upload images in the editor...seems to work ok for me

enriquevaa commented 3 months ago

@ews-grmunjal After I add the icons to my sprite sheet in Mapbox, how do you call them from R, do you have your code? Thanks

ews-grmunjal commented 3 months ago

@enriquevaa -1- I added an icon in svg format to my style (filname: "target2.svg")

-2- Publish the style...some times after publishing there can be a delay in icon being available

then I can just do something like

library(mapgl) library(dplyr) library(sf)

numcolors <- 6 nc <- st_read(system.file('shape/nc.shp', package = 'sf')) nc <- nc %>% mutate(zz = sample(letters[1:numcolors], nrow(.), replace = T)) magma_pal <- viridisLite::magma(numcolors) magma_substr_pal <- substr(magma_pal, 1, 7)

mapboxgl(style = "mapbox://styles/gitanshumunjal/clz3x4vt500o101phh2dn8eiu") %>% fit_bounds(nc, animate = F) %>% add_symbol_layer( id = "target", source = nc, icon_image = "target2" )

which produces

image

walkerke commented 1 month ago

This is now implemented! Here's how to do it (put in your own image in the path):

library(mapgl)

# Path to your local image file
local_image_path <- "/path/to/your/image.png"

pts <- tigris::landmarks("DE")[1:100,]

maplibre(bounds = pts) |> 
  add_image("local_icon", local_image_path) |>
  add_symbol_layer(
    id = "local_icons",
    source = pts,
    icon_image = "local_icon",
    icon_size = 0.5,
    icon_allow_overlap = TRUE
  )

image

Or, try this:

polygons <- tigris::counties("DE", cb = TRUE)

mapboxgl(bounds = polygons) |> 
  add_image("local_icon", local_image_path) |> 
  add_fill_layer(
    id = "pattern-fill",
    source = polygons,
    fill_pattern = "local_icon"
  )

image