javascript クロージャと入出力変数にはまだ問題があります。
私は非営利プロジェクトのために Google マップ API を使用しています。ユーザーはマーカーを gmap に配置し、データベースに地域を (座標とともに) 保存する必要があります。
問題は、場所の緯度と経度の一意のペアを取得するために 2 番目のジオコードを実行する必要がある場合に発生します。たとえば、2 人のユーザーが同じ町にマーカーを配置するとしますが、別の場所にあるとします。同じ地域を持ちたくありません。異なる座標を持つデータベースで 2 回。
ユーザーが地域を選択した後に 2 番目のジオコードを実行できることはわかっていますが、ここで何が間違っているのかを理解したいと思います。
// 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)が台無しになります