Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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: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/

like image 538
Joel Avatar asked Jan 30 '14 18:01

Joel


1 Answers

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 http://jsfiddle.net/6UJQ4/6/

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

Update: http://jsfiddle.net/6UJQ4/7/

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

like image 81
bits Avatar answered Oct 22 '22 19:10

bits