Skip to content

Leaflet : How to create marker labels based on JSON fetched from API

Users are shown points to press. When clicking a point, a menu pops up with text. I’ve been able to set down points, but when I try to retrieve data from my database when clicking a point, it shows does not show the marker specific information.

    for (pointer of pointers) {

        title.textContent = "No description available.";
        if (item.objDescription) {
            title.textContent = item.objDescription;
        }
        div.appendChild(title);

        menu.appendChild(div);
    }
}

Where did I go wrong? I need the pointers to only show their own text and not every textfrom the database.

EDIT :

The issue title was updated to better reflect the desired solution.

Answer

The response is ok, and your code for iterating on the response JSON object seems ok too.

I don’t know what the code for openobjectMenu is, but from what I can see, you are creating the divs and already adding them inside of an element with id objectMenuBody (most likely on your html code). This makes it so that they are visible since the beginning.

I’m guessing you are using Leaflet because of the L.marker on your code.

I think think what you want to do is to add labels to markers, so most likely using the marker.bindPopup("<b>Hello world!</b><br>I am a popup.") is the proper way to go.

You have an example here https://leafletjs.com/examples/quick-start/ .

So instead of this code you wrote :

const div = document.createElement("div");
        const title = document.createElement("h2");
        const lineBreak = document.createElement('br');

        const image = document.createElement("img");
        image.setAttribute("src", "images/default.png");
        image.setAttribute("alt", "Default image");

        title.textContent = "No description available.";
        if (item.objDescription) {
            title.textContent = item.objDescription;
        }
        div.appendChild(title);
        div.appendChild(lineBreak);

You would just directly build a string with the HTML that you should pass to the .bindPopup method.

Quick example:

const pp = `<div><h2>${item.objDescription}</h2><img src="${item.image64}" /></div>`;
const marker = L.marker([item.lat, item.lon]).addTo(map);
marker.bindPopup(pp);