1

I have two visualizations, one D3 and the other Leaflet based. I am trying to get the two to interact. With D3, i can create a object, say a tree map, and i can add IDs or Classes to the nodes with ease. For example:

  var node = div.datum(root).selectAll(".node")
    .data(treemap.nodes)
    .enter().append("rect")
      .attr("class", "node")
      .attr("id", function(d){
        return d.metro_area ? d.metro_area: null;
      }) .....;

I am trying to do the same thing in leaflet where i am creating polygons for metro areas in the US and placing them in a layer on a leaflet map. Similar to this example.

geojson = L.geoJson(statesData, {
      style: style,
      onEachFeature: onEachFeature
  }).addTo(map);

Now on the map, I want to add the metro area's name to the CORRECT polygon in the form of a class or ID.

Doing something like this with D3:

d3.select(map.getPanes().overlayPane).selectAll("path")
.data(polyData).attr("id", function(d){
return d.properties.metro_area.replace(/[\W\s]/g,"");  });

does indeed add IDs to the given polygons, but the order in which the polygons get built and the order in which the metro area names (alphabetical) are returned are different. The two are inconsistent for the most part.

It would seem that in order for the correct metro area to be mapped to the correct polygon on the map, one would need to do something like this:

  function mapToTreeIds(feature){
    return feature.properties.metro_area;
  }
  geojson = L.geoJson(statesData, {
      style: style,
      onEachFeature: onEachFeature,
      addClass: mapToTreeIds
  }).addTo(map);

However the below code does not work of course. There is a L.DOMUtils.hasClass() method, but it does not seem to do the trick. Any ideas? Can this even be done with leaflet version 0.7?

Thanks so much.

Mr. Concolato
  • 2,224
  • 5
  • 24
  • 44

1 Answers1

1

This is a basic difference between D3 and Leaflet: the Leaflet layer abstracts away the DOM & any other way it's shown (like via Canvas), so it limits your access to the underlying elements. You can hack through this abstraction by using private members, but it's not recommended. The Leaflet way is to interact with the elements only through the documented Leaflet API.

tmcw
  • 11,536
  • 3
  • 36
  • 45
  • Thanks for your reply @tmcw, but how to add a class using the L.geoJson method? I am able to get to the DOM elements, but I have a sequence issue. I suspect it can only be resolved through the L.geoJson method, as that is where the geometry polygons get built. – Mr. Concolato Feb 17 '14 at 17:12
  • 1
    I solved my issue and answered it here as someone was having a similar issue here: http://stackoverflow.com/questions/17086195/leaflet-path-how-can-i-set-a-css-class/21637976#21637976 – Mr. Concolato Feb 18 '14 at 15:17