如何在jquery函数内的函数内传递变量?

时间:2013-05-22 17:06:52

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

所以我正在使用谷歌地图API。 我必须在对象内部插入值lat和lon,但我不能做类似的事情:

$.get(url).done(buscaGPS(data, i));

function buscaGPS(data, i) {

}

CODE

objecto = [{
    "address_1": "Avenida da Republica, 15A",
    "city": "Lisbon",
    "country": "pt",
    "id": 1534282,
    "name": "Pastelaria Versailles"
}, {
    "address_1": "Avenida da Republica, 15A",
    "city": "Lisbon",
    "country": "pt",
    "id": 1534282,
    "name": "Pastelaria Versailles"
}];


for (var i = 0; i < objecto.length; i++) {
    var url = "http://maps.googleapis.com/maps/api/geocode/json?address=" + objecto[i].address_1 + "+" + objecto[i].city + "+" + objecto[i].country + "&sensor=false";
    $.get(url).done(buscaGPS);
};



function buscaGPS(data) {

    objecto[i].lat = data.results[0].geometry.location.lat;
    objecto[i].lon = data.results[0].geometry.location.lng;

}

2 个答案:

答案 0 :(得分:1)

听起来你的意思是你想做一些像......

// create a closure to capture the index
function callback(index){
    return function(data) {
        objecto[index].lat = data.results[0].geometry.location.lat;
        objecto[index].lon = data.results[0].geometry.location.lng;
    }
}

for (var i = 0; i < objecto.length; i++) {
    var url = "http://maps.googleapis.com/maps/api/geocode/json?address=" + objecto[i].address_1 + "+" + objecto[i].city + "+" + objecto[i].country + "&sensor=false";
    $.get(url).done(callback(i));
}

答案 1 :(得分:0)

虽然Shanimal的解决方案非常合理,但它通过函数返回函数为代码增加了一些复杂性。你实际上不需要那个来获得一个关闭;一个简单的函数调用就可以了。

考虑这个选择:

for( var i = 0;  i < objecto.length;  i++ ) {
    geocode( objecto[i] );
}

function geocode( place ) {
    var url =
        "http://maps.googleapis.com/maps/api/geocode/json?address=" +
        place.address_1 + "+" + place.city + "+" + place.country +
        "&sensor=false";
    $.get(url).done( function( data ) {
        var location = data.results[0].geometry.location;
        place.lat = location.lat;
        place.lon = location.lng;
    });
}

请注意,这也会删除所有objecto[i]objecto[index]引用,使用简单的place变量来替换它们。

我发现这种方法比返回函数的函数更容易理解。

与地理编码相关的其他评论:您的objecto数组中是否会有更多位置?如果它不止一些,您将需要减慢地理编码请求的速度,而不是连续触发它们。

此外,如果这些是固定位置,您应该对它们进行一次地理编码并将lat / long存储在您的阵列中,这样您就不必在浏览器中对它们进行地理编码。这将使您的地图加载速度更快,并避免对多个地址进行地理编码时出现问题。