如何获得正确的地址与多个"在地图上显示" javascript上的按钮?

时间:2017-05-08 10:10:37

标签: javascript google-maps google-maps-api-3 innerhtml

我正在建立网站,我使用XHR(Ajax)调用来提供有关多个事件的信息。每个活动都有姓名,地址和城市等信息。我使用innerHTML列出了所有这些事件。每个活动都有按钮"在地图上显示"它将标记放入该事件的地址并在谷歌地图上显示。我的问题是每次按下#34;在地图上显示"对任何事件按钮,它会将最后一个事件的地址标记放入地图中。我无法找到使其正常工作的正确方法,因此它使用了正确的地址而不是最后一个。我目前有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
  });
}

1 个答案:

答案 0 :(得分:1)

我认为你应该改变这一部分:

"<button onclick ='geocodeAddress(address)'>Show on map" + "</button>"

"<button onclick ='geocodeAddress(\"' + address + '\")'>Show on map" + "</button>"

目前,您的onclick事件使用全局变量地址的值调用geocodeAddress()函数。全局变量地址包含for循环中最后一个元素的值。