我在向我的R代码添加Leaflet插件时遇到麻烦。具体来说,我正在尝试添加Leaflet.zoomhome插件(请参见this demo的左上角。)
我尝试遵循this guide失败,而这是我到目前为止无法执行的操作。
library(leaflet)
library(htmltools)
library(htmlwidgets)
library(dplyr)
map <-
leaflet::leaflet() %>%
leaflet::addTiles(group = "OSM")
zoom_home_plugin <- htmlDependency(
name = "leaflet.zoomhome",
version = "99.99.99",
src = c(href = "https://github.com/torfsen/leaflet.zoomhome/tree/master/dist/"),
script = "leaflet.zoomhome.js")
RegisterPlugin <- function(map, plugin) {
map$dependencies <- c(map$dependencies, list(plugin))
return(map)
}
map <- RegisterPlugin(map, zoom_home_plugin) %>%
onRender("function(el, x) {
zoomHome.addTo(this);
}")
map
关于导致错误的原因以及如何重写代码以实现插件的任何想法?
谢谢你。
我用此代码得到了一些东西:
library(leaflet)
library(tidyverse)
library(htmlwidgets)
library(htmltools)
map <- leaflet(options = leafletOptions(zoomControl = FALSE)) %>%
addTiles() %>%
onRender(
"
function(el,x) {
var zoomHome = L.Control.zoomHome();
zoomHome.addTo(this);
}
")
temp_folder <- tempdir()
download.file(
"https://raw.githubusercontent.com/torfsen/leaflet.zoomhome/master/dist/leaflet.zoomhome.js",
file.path(temp_folder, 'leaflet.zoomhome.js')
)
download.file(
"https://raw.githubusercontent.com/torfsen/leaflet.zoomhome/master/dist/leaflet.zoomhome.css",
file.path(temp_folder, 'leaflet.zoomhome.css')
)
tagList(
tags$head(
includeScript(file.path(temp_folder, 'leaflet.zoomhome.js')),
includeCSS(file.path(temp_folder, 'leaflet.zoomhome.css')),
tags$link(rel="stylesheet", href="http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css"),
),
map
) %>%
browsable()
据我所知,您的代码正在尝试访问“ https://github.com/torfsen/leaflet.zoomhome/tree/master/dist/”,但是正确的方法是指向“ https://raw.githubusercontent.com/torfsen/leaflet.zoomhome/master/dist/leaflet.zoomhome.js”。即便如此,由于未加载js和样式表(至少在我的所有尝试中),在标头中放置<script>
标记似乎不适用于原始github链接。因此,作为一种解决方法,我将脚本和样式表直接下载到temp文件夹中,并在html标头中使用该文件。
此外,我还添加了fontawesome依赖项并修改了onRender
脚本以匹配leaflet.zoomhome README中的示例>