我仍然对 javascript 闭包和输入/输出变量有一些问题。
我正在使用 google maps api 进行无利润项目:用户将标记放入 gmap,我必须将位置(带坐标)保存在我的数据库中。
当我需要进行第二次地理编码以获得一个位置的唯一 lat 和 lng 对时,问题就出现了:假设两个用户将标记放置在同一个城镇但在不同的地方,我不想拥有相同的位置数据库中有两次不同的坐标。
我知道我可以在用户选择位置后进行第二次地理编码,但我想了解我在这里犯了什么错误:
// First geocoding, take the marker coords to get locality.
geocoder.geocode(
{
'latLng': new google.maps.LatLng($("#lat").val(), $("#lng").val()),
'language': 'it'
},
function(results_1, status_1){
// initialize the html var inside this closure
var html = '';
if(status_1 == google.maps.GeocoderStatus.OK)
{
// do stuff here
for(i = 0, geolen = results_1[0].address_components.length; i != geolen)
{
// Second type of geocoding: for each location from the first geocoding,
// i want to have a unique [lat,lan]
geocoder.geocode(
{
'address': results_1[0].address_components[i].long_name
},
function(results_2, status_2){
// Here come the problem. I need to have the long_name here, and
// 'html' var should increment.
coords = results_2[0].geometry.location.toUrlValue();
html += 'some html to let the user choose the locality';
}
);
}
// Finally, insert the 'html' variable value into my dom...
//but it never gets updated!
}
else
{
alert("Error from google geocoder:" + status_1)
}
}
);
我尝试过:
// Second type of geocoding: for each location from the first geocoding, i want
// to have a unique [lat,lan]
geocoder.geocode(
{
'address': results_1[0].address_components[i].long_name
},
(function(results_2, status_2, long_name){
// But in this way i'll never get results_2 or status_2, well, results_2
// get long_name value, status_2 and long_name is undefined.
// However, html var is correctly updated.
coords = results_2[0].geometry.location.toUrlValue();
html += 'some html to let the user choose the locality';
})(results_1[0].address_components[i].long_name)
);
与:
// Second type of geocoding: for each location from the first geocoding, i want to have
// a unique [lat,lan]
geocoder.geocode(
{
'address': results_1[0].address_components[i].long_name
},
(function(results_2, status_2, long_name){
// But i get an obvious "results_2 is not defined" error (same for status_2).
coords = results_2[0].geometry.location.toUrlValue();
html += 'some html to let the user choose the locality, that can be more than one';
})(results_2, status_2, results_1[0].address_components[i].long_name)
);
有什么建议吗?
编辑:
我的问题是如何将附加参数传递给地理编码器内部函数:
function(results_2, status_2, long_name){
//[...]
}
因为如果我这样做的话,我会弄乱原始参数(results_2 和 status_2)