I'm working on a Word document with a leaflet maps. In RStudio the leaflet maps works good, but when I Knit my Word document with Rmarkdown, no map appears in Word. I recently change my computer and reinstall Rstudio, before that the leaflet maps works fine with Word.
The code below is the code in RMarkdown document.
---
author: "Autor"
title: "Informe"
subtitle: "Programa"
date: "`r format(Sys.time(), '%d de %B, %Y')`"
output:
officedown::rdocx_document:
plots:
style: Normal
align: center
caption:
style: Image Caption
pre: 'Figura '
sep: ': '
tables:
style: Table
layout: autofit
width: 1.0
caption:
style: Table Caption
pre: 'Tabla '
sep: ': '
conditional:
first_row: true
first_column: false
last_row: false
last_column: false
no_hband: false
no_vband: true
page_size:
width: 8.3
height: 11.7
orient: "portrait"
page_margins:
bottom: 1
top: 1
right: 1.25
left: 1.25
header: 0.5
footer: 0.5
gutter: 0.5
bibliography: referencias.bib
csl: apa-6th-edition.csl
always_allow_html: true
editor_options:
markdown:
wrap: 72
chunk_output_type: console
---
library(leaflet)
library(officedown)
library(officer)
leaflet::leaflet() %>% addTiles()
I rebooted my PC, and reinstalled leaflet package.
Did you try to set caching to false? See discussion here.
```{r}
#| label: fig-geolocation
#| fig-cap: Geolocation of participants
#| cache: no
#| echo: false
leaflet::leaflet() |> leaflet::addTiles()
```
Also, there is an old trick as well: save map as widget and then import it as image file.
```{r}
#| label: fig-geolocation
#| fig-cap: Geolocation of participants
#| echo: false
map <- leaflet::leaflet() |>
leaflet::addTiles()
htmlwidgets::saveWidget(widget = map,
file = "temp.html",
selfcontained = FALSE)
webshot::webshot(url = "temp.html",
file = "map.png",
cliprect = "viewport") # cliprect = c(200, 5, 400, 300))
```
EDIT:
According to Yihui Xie, "if you include an HTML widget in a non-HTML output format, such as a PDF, knitr will try to embed a screenshot of the widget if you have installed the R package webshot (Chang 2023)...". Also valid for Word (non-HTML output format).