在我的 Web 應用程式中,用戶會看到一張帶有標記的地圖,他們可以按下這些標記。單擊標記時,將顯示帶有影像和文本的詳細資訊視圖。影像和文本從資料庫中檢索,并且對于標記是唯一的(每個標記具有不同的影像和文本)。我已經能夠設定標記,并將資訊保存到資料庫中,但是當我嘗試在單擊標記時從我的資料庫中檢索特定標記的資料時,它會顯示從資料庫中檢索到的所有內容,而不是特定于標記的資訊。
async function getData() {
const response = await fetch('/api');
const data = await response.json();
for (item of data) {
// This prints the markers in the co-ordinates stored in the database.
L.marker([item.lat, item.lon]).addTo(map).on('click', openobjectMenu);
// This is meant to give the markers their specific text and image.
const objectMenu= document.querySelector("#objectMenuBody");
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);
objectMenu.appendChild(div);
}
}
這是列印標記并為標記提供存盤在資料庫中的資訊的代碼。但是,例如,單擊柏林中的標記并在物件視圖中顯示“柏林測驗”,它顯示:
SHANGHAI TEST
LONDON TEST
BERLIN TEST
USA TEST
MOSCOW TEST
我哪里做錯了?我需要標記只顯示它們的特定描述 (objDescription),而不是資料庫中的每個描述。
編輯 :
問題標題已更新,以更好地反映所需的解決方案。
uj5u.com熱心網友回復:
回應沒問題,您用于迭代回應 JSON 物件的代碼似乎也沒問題。
我不知道代碼openobjectMenu是什么,但據我所知,您正在創建 div 并已經將它們添加到帶有 id 的元素中objectMenuBody(很可能在您的 html 代碼中)。這使得它們從一開始就可見。
我猜你正在使用 Leaflet 因為L.marker你的代碼。
我認為您想要做的是為標記添加標簽,因此很可能使用marker.bindPopup("<b>Hello world!</b><br>I am a popup.")是正確的方法。
你在這里有一個例子https://leafletjs.com/examples/quick-start/。
所以你寫的不是這段代碼:
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);
您只需使用應傳遞給該.bindPopup方法的 HTML 直接構建一個字串。
快速示例:
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);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/337260.html
標籤:javascript 数组 数据库 表达 传单
上一篇:如何將日期合并為一列?
下一篇:重復資料洗掉記錄(視窗函式熊貓)
