0

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.

3
2

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);
};
3
  • It works!!! Thank you again @TomazicM!
    – BallpenMan
    Sep 23 at 11:55
  • Btw, is it possible to use the json layer's name instead of its style name? I'm asking because I want the styling and popup to be a single function which requires the if statement to call the layer's name like if(json=lyrBldgs){}. @TomazicM
    – BallpenMan
    Sep 23 at 13:34
  • No, since main GeoJSON layer is not a parameter to onEachFeature option function. As I wrote in the answer, the best would be some property of features, since feature is on of the parameters for the mentioned function.
    – TomazicM
    Sep 23 at 16:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.