-1

我正在尝试获取 N 个地址,并能够在 N 个 Google 地图上显示这些地址。我有 N 个 div 元素,其 class 属性设置为“canvas”。当我运行我的代码时,最后一个表格单元格元素包含我需要的位置的地图。其他表格单元格均不包含地图。

JavaScript:

// JavaScript Document

var geocoder;
var mapOptions;
var newLocation;
var element;

$(document).ready(function()
{

    $.each($(".canvas"),function(i,value)
    {   
        element = value;
        initialize($("tr").eq(i).children("td").text());
    });
});

function initialize(tr) 
{
geocoder = new google.maps.Geocoder();
codeAddress(tr);

}

function codeAddress(address) 
{       
    geocoder.geocode({ 'address': address}, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            newLocation = results[0].geometry.location;
            mapOptions = 
            {
                center: new google.maps.LatLng(newLocation.Ya,newLocation.Za),
                zoom: 10,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            }
            map = new google.maps.Map(element, mapOptions);

        } else {
            alert('Geocode was not successful for the following reason: ' + status);
        }
    });
}

HTML:

  <html>
      <head>
      </head>
      <body>
         <table>
             <tr>
                  <td>Address 1</td><td class="canvas"></td>
                  <td>Address 2</td><td class="canvas"></td>
                  <td>Address 3</td><td class="canvas"></td>
                  <td>Address 4</td><td class="canvas"></td>
                  <td>Address 5</td><td class="canvas"></td>
                  <td>Address 6</td><td class="canvas"></td>
             </tr>
         </table>
     </body>
  </html>
4

1 回答 1

0

element您在每个循环中覆盖$.each() .

将其作为参数传递给codeAddress

$.each($(".canvas"),function(i,element)
    {   
        initialize($(element).prev().text(),element);
    });

......

function codeAddress(address,element){
  //your code
} 
于 2013-02-18T10:17:50.543 回答