从回调中识别对象

时间:2011-09-08 23:59:51

标签: jquery google-maps

我正在使用谷歌地图地理编码地址以便在地图上显示。我循环遍历每个地址并通过jquery回调处理响应。

如何识别回电来自哪个项目?

var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': addr }, function (results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
        var marker = new google.maps.Marker({ position: results[0].geometry.location, map: map, title: "Yo Homie" });
        // I need to find the item to setup the infowindow
        bounds.extend(results[0].geometry.location);
        map.fitBounds(bounds);
    }
    else {
        // eat it like a mexican jumping bean
    }
});

2 个答案:

答案 0 :(得分:1)

我将地理编码器调用包装到一个函数中,将您的对象传递给该函数,然后您也可以在地理编码器的回调中使用它。

示例:

// i'm just staging a fake for loop here... 
for(var i = 0; i < 10; i++){

    // this is your basic object
    var obj = {address: "Brussels Belgium"};
    // here you call the geo function and pass the object so that you can access it inside the function
    doGeoCode(obj);
}

function doGeoCode(obj) {
  // your geocoder wrapped in a function, takes 1 argument which you can reference in the callback below
  var geocoder;
  geocoder = new google.maps.Geocoder();
  geocoder.geocode( { 'address': obj.address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      var p = results[0].geometry.location;

      // inside this callback function you can just reference 'obj' 
      obj.position = {'longitude': p.lng(), 'latitude': p.lat()};
    } else {
      // your mexican thingy
    }
  });
}

答案 1 :(得分:0)

请您提供更多代码? 查看当前代码,我假设您发布的所有代码都在循环内,而addr是您列表的单个地址。如果是这样,那么您应该可以在回调函数(结果,状态)中访问addr。