1

I currently have a popup in Mapbox that displays some properties and a photo. Not all of the points have photos though, so the ones that have a null value in the image link field just show a blank box where the photo would be. I want to set it so that any features that have a null value in this field only show the text in the popup and not the image link part.

enter image description here

Here's the popup code I have so far:

  var popup = new mapboxgl.Popup({ offset: [0, 0] })
    .setLngLat(e.lngLat)
    .setHTML('<p>' + feature.properties.Name + '<br>' + feature.properties.PopupInfo + '<br> <img src="' + feature.properties.image_link +'" style="width:200px;height:125px;">' + ' </p>')
    .addTo(map);

I found this question that seems to address the issue, but I'm fairly new at Javascript, and I'm having trouble understanding how exactly I would implement this in my scenario. https://stackoverflow.com/questions/55106852/show-not-null-attributes-in-mapbox-gl-js-popups

Here's the code given in that example:

const feature = {
  properties: {
    attr1: 'text',
    attr2: null,
    attr3: 42,
    attr4: null,
    ...
  }
};

const popupContent = Object
  .keys(feature.properties)
  .reduce((acc, property) => {
    const value = feature.properties[property];

    // your condition here
    if (value) {
      acc.push(`${property}: ${value}`);
    }

    return acc;
  }, [])
  .join(', ');

console.log(popupContent) // attr1: text, attr3: 42

I think I'd have to replace the .join part with .concat and add in the HTML text I want and then pass that back into .setHTML in the popup var, but I can't figure out how to pass my properties into this and then how to get it back into the mapbox.Popup part.

2

You can simply use something like:

var popupContent = '<p>' + feature.properties.Name + '<br>' + feature.properties.PopupInfo + '<br>'
popupContent += feature.properties.image_link ? '<img src="' + feature.properties.image_link +'" style="width:200px;height:125px;"> </p>' : ' </p>'

var popup = new mapboxgl.Popup({ offset: [0, 0] })
        .setLngLat(e.lngLat)
        .setHTML(popupContent )
        .addTo(map);

What it does, is checks if there is an imagelink property (and that it's not null) and if there isn't simply closes the paragraph.

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.