我认为 rMaps 库中可能存在一个小问题。如果您检查 config.yml 文件
https://github.com/ramnathv/rCharts/blob/master/inst/libraries/leaflet/config.yml 你会看到
内容分发网络(cdn)有参考
“http://harrywood.co.uk/maps/examples/leaflet/leaflet-plugins/layer/vector/KML.js”。这个 KML 阅读器是来自https://github.com/shramov/leaflet-plugins/blob/master/layer/vector/KML.js 的传单插件。当内容在本地交付时:
css: [external/leaflet.css, external/leaflet-rCharts.css, external/legend.css]
jshead:
- external/leaflet.js
- external/leaflet-providers.js
- external/Control.FullScreen.js
没有对此 javascript 文件的引用。我们可以解决这个问题:
require(yaml)
leafletLib <- file.path(find.package("rMaps"), "libraries", "leaflet")
rMapsConfig <- yaml.load_file(file.path(leafletLib, "config.yml"))
# add a kml library
kmlLib <- readLines("http://harrywood.co.uk/maps/examples/leaflet/leaflet-plugins/layer/vector/KML.js")
write(kmlLib, file.path(leafletLib, "external", "leaflet-kml.js"))
# add the library to config.yml
rMapsConfig$leaflet$jshead <- union(rMapsConfig$leaflet$jshead , "external/leaflet-kml.js")
write(as.yaml(rMapsConfig), file.path(leafletLib, "config.yml"))
现在config.yml 将包含指向 KML 阅读器的必要链接,并且现在在 external/leaflet-kml.js 中存储了一个本地副本。但是,我们的示例仍然无法正常工作,因为我们将获得 Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://kml-samples.googlecode.com/svn/trunk/kml/Placemark/placemark.kml. 这可以通过将资源移动到同一域或启用 CORS 来解决。
我们需要在本地提供此文件。我们可以将它作为临时措施放在 rMaps 包中的小册子文件夹中。创建地图时,此文件夹会被复制到临时文件中:
require(rMaps)
map1 = Leaflet$new()
map1$setView(c(45.5236, -122.675), 13)
map1$tileLayer("http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png")
map1$addKML('leaflet/placemark.kml')
# temp copy http://kml-samples.googlecode.com/svn/trunk/kml/Placemark/placemark.kml
# to rMaps
sampleKml <- readLines('http://kml-samples.googlecode.com/svn/trunk/kml/Placemark/placemark.kml')
write(sampleKml, file.path(leafletLib, 'placemark.kml'))
# finally try the map
map1
# remove the temp file
file.remove(file.path(leafletLib, 'placemark.kml'))
更新:
在rCharts 中有一个addAssets 方法,它允许您添加.js 文件。这使我们可以简化事情,不需要我们编写 js 文件的副本,也不需要编辑 config.yml 文件。
require(rMaps)
map1 = Leaflet$new()
map1$setView(c(45.5236, -122.675), 13)
map1$tileLayer("http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png")
map1$addAssets(css = NULL, jshead = 'http://harrywood.co.uk/maps/examples/leaflet/leaflet-plugins/layer/vector/KML.js')
map1$addKML('leaflet/placemark.kml')
leafletLib <- file.path(find.package("rMaps"), "libraries", "leaflet")
sampleKml <- readLines('http://kml-samples.googlecode.com/svn/trunk/kml/Placemark/placemark.kml')
write(sampleKml, file.path(leafletLib, 'placemark.kml'))
# finally try the map
map1
# remove the temp file
file.remove(file.path(leafletLib, 'placemark.kml'))