1

I tried the most basic code for leaflet in rstudio:

library(leaflet)
m <- leaflet()
m <- addTiles(m)
m <- addMarkers(m, lng=174.768, lat=-36.852, popup="The birthplace of R")
m

When I run it as a script, nothing happens, the m object is not created, no other errors are given. However, if I run it line by line, it gives the expected output - object m is created and the map is printed.

What can be the problem? ChatGPT could not tell. I reinstalled and updated everything, all libraries and Rstudio itself.

2
  • 1
    Welcome to SO! Can you be more specific on "run it as a script" ? The Source button? You probably want it as a part of RMarkdown or Quarto document that you can knit or render to html.
    – margusl
    Commented Dec 22, 2023 at 8:58
  • try adding print(m) to your script.
    – Dave2e
    Commented Dec 22, 2023 at 14:38

1 Answer 1

0

Install all the packages before you try this:

library(leaflet)
library(htmlwidgets)

m <- leaflet() %>%
    addTiles() %>%
    addMarkers(lng = 174.768, lat = -36.852, popup = "The birthplace of R")

saveWidget(m, file = "leaflet_map.html", selfcontained = TRUE)
system(paste0("cmd /c start leaflet_map.html"))

Let me know if this worked for you.

For me the above got opened in system default browser. I am using Windows PC.

for Mac / Linux, you should use:

system("open leaflet_map.html") 

Not the answer you're looking for? Browse other questions tagged or ask your own question.