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.

Kadir Şahbaz
78.6k57 gold badges260 silver badges407 bronze badges
asked Dec 23, 2020 at 20:27

1 Answer 1

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.

answered Dec 24, 2020 at 5:07

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.