Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make appearance of clustered icon related to statistics of the children?

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?

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.

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>'});

  }")

  )
)

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.

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

like image 639
yosukesabai Avatar asked Oct 20 '25 07:10

yosukesabai


1 Answers

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>'});
  }")
  )
)
like image 63
yosukesabai Avatar answered Oct 22 '25 20:10

yosukesabai