开发者

Identifying the object from a callback

I'm working with google maps to geocode addresses for display on a map. I'm looping through each address and handling the response through a callback via jquery.

How can I identify which item the call back is from?

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
    }
});


i wrap the geocoder call into a function, pass your object into that function then you can use it in the callback of geocoder as well.

example:

// 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
    }
  });
}


May you provide more code please? Looking at your current code I assume that all the code you posted is inside the loop and addr is a single address of your list. If so, you should have access to addr inside your callback function(results,status) then.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜