I'm working on a map that uses leaflet and is populated by data from a file in a GeoJson format. My overarching goal is to put graphs into the leaflet popups for each marker on the map.
Getting the markers for each feature and getting the popups to open was fairly easy. However, I am finding it difficult to use D3 to add to the popup.
For the sake of simplicity my goal at the moment is to use D3 to create a svg within each leaflet popup div and draw a square.
I have found some examples where people have used D3 to create graphs inside leaflet popups, but none of them were also using geoJson and the onEachFeature function. This is one of the examples:http://jsfiddle.net/6UJQ4/
Here is the relevant part of my code:
L.geoJson( data, {
style: function (feature) {
return { opacity: 0, fillOpacity: 0.5, fillColor: "#0f0" };
},
onEachFeature: function(feature, layer){
var graph_container = '<div class="popupGraph" id="graph" style="width: 200px; height:200px;"></div>';
layer.bindPopup(feature.properties.name + '<br>' + graph_container);
var svg = d3.select("#graph").selectAll("svg").append("svg").attr("width", 50).attr("height", 200);
var rectangle = svg.append("rect").attr("width", 25).attr("height", 25);
}
}).addTo(map);
I believe I am having issues because D3 can't find the graph_container div however I am a little stumped on how to fix this.
If anyone has any experience using D3, Leaflet, and geoJson together and could explain to me how to get my square to show in the popups or if anyone knows of a source that could help me. I would appreciate it a lot. Thanks in advance!
UPDATE: Bits has solved my problem! If anyone needs a working example of using D3 in Leaflet popups in combination with GeoJson, Bits posted it in the comments but I will post it here aswell: http://jsfiddle.net/2XfVc/132/
.append()
. What you're creating ingraph_container
is really only a string and won't change anything on the page. – Lars Kotthoffsvg
element could be appended to the newly inserteddiv
programatically afterwards. IMO It doesn't have to be added to DOM before you can use D3. – bitsbindPopup
andopenPopup
will take care of converting the div's string into actual DOM. – bits