yosukesabai
yosukesabai

Reputation: 6244

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 ...?

Upvotes: 4

Views: 2568

Answers (1)

yosukesabai
yosukesabai

Reputation: 6244

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

Upvotes: 6

Related Questions