传单R,如何使与儿童统计相关的聚集图标出现?

2022-01-12 00:00:00 r leaflet javascript

我想根据子标记的属性总和在 Leaflet/Shiny 应用程序中自定义聚集标记的外观.

I'd like to customize appearance of clustered markers in Leaflet/Shiny application based on sum of an attribute of child markers.

类似于这个问题,它根据孩子的数量制作集群的图标颜色.如果我想根据地震震级和自定义图标怎么办?

It is similar to this problem, which makes icon color of clusters based on count of children. What if I want to customize icon based on the sum of magnitude of earthquakes?

使用纯 javascript 应用程序,似乎我应该能够将自定义属性设置为单个标记,然后从 iconCreateFunction 访问它,就像在 这个例子.

With pure javascript application, seems like I should be able to set custom property to individual marker, then access it from iconCreateFunction, as done in this example.

但是我正在为 R 的传单添加带有 addCircleMarkersaddMarkers 的标记,并且似乎我不能为正在生成的标记添加任意属性.下面的代码有效,但如果我取消注释两行(mag = ~magsum += markers[i].mag;)

But I am adding marker with addCircleMarkers and addMarkers from leaflet for R, and doesn't seem i can add arbitrary attribute to markers being generated. Code below works but it doesn't if i uncomment two lines (mag = ~mag and sum += markers[i].mag;)

leaflet(quakes) %>% addTiles() %>% addMarkers(
  # mag = ~mag,
  clusterOptions = markerClusterOptions(
  iconCreateFunction=JS("function (cluster) {    
    var markers = cluster.getAllChildMarkers();
    var sum = 0; 
    for (i = 0; i < markers.length; i++) {
    //  sum += markers[i].mag;
      sum += 1;
    }
    return new L.DivIcon({ html: '<div><span>' + sum + '</span></div>'});

  }")

  )
)

我想过使用 addMarkerslabel= 选项,然后从 Javascript 中解析它.但是在 JS 的标记簇上使用 getAllChildMarkers() 访问的标记似乎没有 label 属性.

I thought about using label= option of addMarkers, and then parse it from Javascript. But the markers accessed with getAllChildMarkers() on marker cluster in JS does not seem to have label property.

我还考虑过将数据帧从 R 传递到传单(JS),不知何故,也许 喜欢这个例子,或 this ...?

I also thought about passing a dataframe from R to leaflet(JS), somehow, maybe like this example, or this ...?

推荐答案

找到了我的答案.似乎我可以在 addMarkeroptions= 中放置任意属性:

Found my answer. Seems like I can put arbitrary property inside options= in addMarker:

leaflet(quakes) %>% addTiles() %>% addMarkers(
  options = markerOptions(mag = ~mag),
  clusterOptions = markerClusterOptions(
  iconCreateFunction=JS("function (cluster) {    
    var markers = cluster.getAllChildMarkers();
    var sum = 0; 
    for (i = 0; i < markers.length; i++) {
      sum += Number(markers[i].options.mag);
//      sum += 1;
    }
    return new L.DivIcon({ html: '<div><span>' + sum + '</span></div>'});
  }")
  )
)

相关文章