首页 > 解决方案 > 在 R 传单中使用 Java Script htmlwidget 指定点半径

问题描述

我正在使用此处提供的(非常有用的)代码https://github.com/timelyportfolio/leaftime/blob/master/inst/examples/example_leaftime.R 使用 R 中的传单构建时间序列图。我似乎无法弄清楚如何在我的地图上定义每个点的半径,并希望有人能指出我正确的方向。

我的测试数据如下:

data <- data.frame(

"latitude" = c(36.998953, 38.998607, 40.547953, 36.475103, 34.634023),

"longitude" = c(-78.766255, -81.051412, -78.969508, -83.298121, -78.541041),

"start" = seq.Date(as.Date("2009-01-01"), by="day", length.out = 5),

"end" = seq.Date(as.Date("2009-01-01"), by = "day", length.out = 5) + 1,

"radius" = c(10, 8, 5, 12, 7)

)

我可以使用这里的代码创建一个基本的时间序列图:

library(leaflet)
library(leaftime)
library(htmltools)
library(geojsonio)
library(geojsonlint)

leaflet(geojsonio::geojson_json(data, lat="latitude", lon="longitude")) %>%
  addTiles() %>%
  setView(-79.771504, 36.854041, 2) %>%
  addTimeline(
    sliderOpts = sliderOptions(
      formatOutput = htmlwidgets::JS("function(date) {return new 
      Date(date).toDateString()}"), position = "bottomright", duration = 3000),
    timelineOpts = timelineOptions(
      styleOptions = styleOptions(radius = 5, color = "black", fillColor = "blue", fillOpacity = 0.60)))

但是修改此代码以自定义每个点的半径不起作用:

leaflet(geojsonio::geojson_json(data, lat="latitude", lon="longitude")) %>%
  addTiles() %>%
  setView(-79.771504, 36.854041, 2) %>%
  addTimeline(
    sliderOpts = sliderOptions(
      formatOutput = htmlwidgets::JS("function(date) {return new 
      Date(date).toDateString()}"), position = "bottomright", duration = 3000),
    timelineOpts = timelineOptions(
      styleOptions = styleOptions(radius = htmlwidgets::JS("function getRadius(d) {return +d.properties.radius}"), 
      color = "black", fillColor = "blue", fillOpacity = 0.60)))

从JS htmlwidget调用java脚本函数getRadius时似乎出现错误,但我不熟悉java脚本语言,不知道如何修复。谢谢你的帮助!

标签: javascriptrleaflethtmlwidgetsr-leaflet

解决方案


如果您的意思是它的 JS 代码,请尝试:function getRadius(d) {return d.properties.radius}


推荐阅读