Making a graph inside a leaflet popup using geoJson data

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:

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( + '<br>' + graph_container);    

        var svg ="#graph").selectAll("svg").append("svg").attr("width", 50).attr("height", 200);   

        var rectangle = svg.append("rect").attr("width", 25).attr("height", 25);


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:


Its quite simple, you just need to add and svg element inside of your div. And start coding d3.

Give me a moment, I am updating your fiddle.

Update: Here you go

I took the liberty of simplifying/stripping your example to lowest common denominator to reduce confusion.


In the previous fiddle, you will come across issues where all your markers will be selected everytime giving undesired results. So use last update.

Need Your Help

Hiding Internationalization with the Repository Pattern

c# design-patterns internationalization repository-pattern

I'm trying to create an internationalized shop as an example. In order to expose Product which has different translations for each property.