我正在制作网站,在其中使用 XHR(Ajax)调用提供有关多个事件的信息。每个事件都有名称、地址和城市等信息。我使用innerHTML 列出了所有这些事件。每个事件都有“在 map 上显示”按钮,该按钮将标记该事件的地址并将其显示在谷歌地图上。我的问题是,每次我在任何事件上按下“在 map 上显示”按钮时,它都会将最后一个事件的地址标记放入 map 中。我无法找出使其工作的正确方法,因此它使用正确的地址,而不总是最后一个。我当前有 10 个事件(因为 info.length 为 10),但所有 10 个按钮都将标记放在同一个位置。感谢所有帮助!
我是这样做的:
function bringInfo() {
var info = JSON.parse(req.responseText);
for (var i = 0; i < info.length; i++) {
header = info[i].title;
description = info[i].description;
address = info[i].contact_info.address;
city = info[i].contact_info.city;
link = info[i].contact_info.link;
pic = info[i].image.src;
makeEvent(header,description,address,city,link,pic);
}
}
我使用 InnerHTML 制作事件的函数:
function makeEvent(header, description, address, city, link, pic) {
var newDiv = document.createElement('div');
var containerElem = document.getElementById('container');
var eventHTML = "<div class = 'panel'> <h1 id ='header'>" + header + "</h1>" +
"<img src = '" + pic + "'>" +
"<p>" + description + "</p>" +
"<p>Address:" + address +"</p>" +
"<p>City:" + city +"</p>" +
"<p>Link: <a href ='" + link + "'>" + link + "</a></p>" +
"<button onclick ='geocodeAddress(address)'>Show on map" + "</button>";
newDiv.innerHTML = eventHTML;
newDiv.className += "panel";
containerElem.appendChild(newDiv);
}
编辑:
var myMap;
function geocodeAddress(address) {
var coder = new google.maps.Geocoder();
coder.geocode({'address': address}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
myMap.setCenter(results[0].geometry.location);
putMarker (results[0].geometry.location, address);
} else {
alert('Geocoding didnt work. Reason: ' + status);
}
});
}
function putMarker(p, text) {
var ownMarker =
new google.maps.Marker({
position: p,
map: myMap,
title: text
});
}
function initMap() {
myMap = new google.maps.Map(document.getElementById('map'), {
center: {lat: 33.33, lng: 33.33},
zoom: 15
});
}
最佳答案
我认为你应该更改这部分:
"<button onclick ='geocodeAddress(address)'>Show on map" + "</button>"
到
"<button onclick ='geocodeAddress(\"' + address + '\")'>Show on map" + "</button>"
当前,您的 onclick 事件使用全局变量地址的值调用 geocodeAddress() 函数。全局变量地址包含 for 循环中最后一个元素的值。
关于javascript - 如何在javascript上使用多个 "show on map"按钮获取正确的地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43844965/