如何从JavaScript数组中提取数据库中的所有元素?

时间:2015-04-13 18:24:29

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

我需要在地图上放置谷歌地图标记,这是我要用于此任务的代码:

  function codeAddress() {
    var address = document.getElementById('address').value;
    geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        map.setCenter(results[0].geometry.location);
        var marker = new google.maps.Marker({
            map: map,
            position: results[0].geometry.location
        });
      } else {
        alert('Geocode was not successful for the following reason: ' + status);
      }
    });
  }

现在这个脚本有效,但是我想修改它以便与地址数组一起使用。你能告诉我怎么做吗?我会从php SQL循环中获取地址。

1 个答案:

答案 0 :(得分:1)

我会修改你的函数以接受地址作为参数:

function codeAddress(address) {
    geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        map.setCenter(results[0].geometry.location);
        var marker = new google.maps.Marker({
            map: map,
            position: results[0].geometry.location
        });
      } else {
        alert('Geocode was not successful for the following reason: ' + status);
      }
    });
  }

然后当你得到数组数据时,循环它并调用你的函数。

var addresses; // array of address

for (index = 0; index < addresses.length; ++index) {
    codeAddress(addresses[index]);
}