[GIS] Have to click twice to open popup leaflet

geojsonleaflet

I am trying to make a map in which a marker can be clicked and a popup opens up with some information. I have successfully done all of that however my first click on any of the markers result in the popup being placed randomly on the map. If I click again, the popup will place itself correctly (on top of the marker). I believe that I am doing something wrong when calling the "onEachFeature" function. Here is the code:

    // Importing the data from the geojson
$.getJSON("data/factories.geojson", function(data)
{
    factories = L.geoJson(data, {
        pointToLayer: function(feature, latlng)
        {
            return L.circleMarker(latlng, style);
        },
        onEachFeature: onEachFeature,
        style: style
    }).addTo(map);
});
// Action for each feature of the choropleth
function onEachFeature(feature, layer)
{
    console.log("onEachFeature");
    layer.on({
            click: highlightSelection
    });
}
// Highlighting the selected administrative area
function highlightSelection(e)
{
    // Some code her to add text and image to the popup
    factories.bindPopup(image + text);

    **// This will reset the highlight of the previously clicked marker
    if(firstPass == false)
    {
        console.log(lastLayer);
        resetHighlight(feature, lastLayer);
    }
    lastLayer = layer;
    firstPass = false;
    layer.on({
        click: function(){
            layer.setStyle({
                        radius: 14,
                        weight: 2,
                        opacity: 0,
                        fillColor: '#FFCC00',
                        fillOpacity: 0.8
                    });
        }
    })**
}

**// Reset any highlights after mouseout
function resetHighlight(lastLayer)
{
    layer.resetStyle(lastLayer);
}**

Best Answer

I don't think you will need to call the highlightSelection function, try to update the onEachFeature function to something like the one below to append content to popup window for each layer:

// Action for each feature of the choropleth
function onEachFeature(feature, layer)
{
    console.log("onEachFeature");
    layer.bindPopup('hello, popup');
//    layer.on({
//            click: highlightSelection
//    });
}