General JavaScript function handling popups of various JSON layers in a Leaflet map

ajaxgeojsonif statementleafletpopup

I have a couple of JSON layers added to my Leaflet map via the leaflet-ajax plugin.

lyrBldgs = new L.GeoJSON.AJAX('data/bldgs.geojson', {style:stlBldgs, onEachFeature:popOSM}).addTo(mymap)
lyrLanduse = new L.GeoJSON.AJAX('data/landuse.geojson', {style:stlNaturalLUse, onEachFeature:popOSM});
lyrNatural = new L.GeoJSON.AJAX('data/natural.geojson', {style:stlNaturalLUse, onEachFeature:popOSM});

The popOSM function that handles the pop-up is

function popOSM(json){
    if(json=lyrBldgs){
        json.bindPopup("Bldgs")
    } else if(json=lyrLanduse) {
        json.bindPopup("Landuse")
    } else {
        json.bindPopup("Natural")
    };
};

However, the popup only works for the buildings layer and not for the other layers. The problem seems to be that the if statement does not run after the first if condition.

Best Answer

There are several things wrong in your approach. First thing that is wrong is that comparison in JS uses == or ===, single = is used for assignment.

Second thing that is wrong is the way you define and use onEachFeature option function. Function has two parameters, first parameter being one feature of the GeoJSON and the second parameter being layer, created on the basis of this feature, and that will be added to group layer consisting final GeoJSON layer (see https://leafletjs.com/reference-1.7.1.html#geojson).

If you want to use single onEachFeature function for all GeoJSON layer, you need some property/parameter that will tell you to which GeoJSON layer feature belongs. This is usually some feature property, but in your case it can be also feature layer style. Since I don't know the structure of your GeoJSON data, I'll use style in the code below.

Relevant part of the code could then look something like this:

function popOSM(feature, layer){
  var layerStyle = layer.options.style;
  var popupTxt;
  if (layerStyle == stlBldgs)
    popupTxt = 'Bldgs';
  else if (layerStyle == stlLanduse)
    popupTxt = 'Landuse';
  else {
    popupTxt = 'Natural';
  };
  layer.bindPopup(popupTxt);
};