2017-06-23 7 views
0

経度と緯度を返し、それらを空の緯度と経度の配列にプッシュするだけです。私の問題は、私がアラート(lat [0])すると、それは未定義となり、コールバック関数でアラートを使用するのではなく、これらの値にアクセスできるようにしたいということです。これを回避する方法はありますか?どんな助けでも大歓迎です!Google APIから緯度と経度を返して配列に渡す

var lat=[]; 
var lon=[]; 
var geocoder = new google.maps.Geocoder(); 
geocoder.geocode({ 'address': 'miami, us'}, function(results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
     lat.push(results[0].geometry.location.lat()); 
     lon.push(results[0].geometry.location.lng()); 
     } else { 
     alert("Something got wrong " + status); 
     } 
    }); 
alert(lat[0]); 
alert(lon[0]); 
+0

は 'geocode'メソッド同期のですか?それとも非同期ですか? –

+0

まだ定義されていない変数に到達しようとしています。これは、 'geocoder.geocode'の' callback'関数がまだ呼び出されていないためです。だからあなたは '未定義 'になる。 'else'ステートメントの直前の括弧の直後にあなたのアラートを置き換えてみてください。そして、あなたのコーズが表示されます –

+0

素早く応答してくれてありがとう!それでもまだ動作していません。どうやらそれは非同期です。また、else文の直後にアラートを置くと、アラートは機能しますが、ジオコードブロックの外側にはアクセスしません(これはアクセスする必要があります) –

答えて

0

私は問題を自分で解決しました。私の解決策では、都市のリストを取り込み、API呼び出しを介してそれらをジオコードします。最後の呼び出しが戻されると、Mainというコールバック関数が実行されます。関数Mainは、読み込まれたlatsとlonsの配列にアクセスできる場所です。ここで

//Here is an array of locations to be geocoded 
var locations1 = []; 
locations1.push("Horsham, PA"); 
locations1.push("Dallas, TX"); 
locations1.push("Chicago, IL"); 
locations1.push("Denver, CO"); 
locations1.push("San Diego, CA"); 

// Create an array to store the latitudes and longitudes 
var lat1=[]; 
var lon1=[]; 

//create time parameter to delay each call, limited number of calls per 
//second 
var time=0; 

//loop through each location and call the geo function 
for (var i = 0; i < locations1.length; i++) { 
    geo(locations1[i],time); 
    time=time+1; 
} 

// inputs a location and time parameter then adds the lat/lon to array 
function geo(loc,t){ 

    var geocoder = new google.maps.Geocoder(); 
    setTimeout(function(){ 
    geocoder.geocode({ 
     'address': loc 
    }, function(results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
     lat1.push(results[0].geometry.location.lat()); 
        lon1.push(results[0].geometry.location.lng()); 

     } else { 
     alert("Something got wrong " + status+ " problem with: "+ loc); 
     } 
     // When your array is full run main, this is where you can do 
//things with the array 
     if(lat1.length==locations1.length){ 
     main(); 

     } 

    }); 
    },t*1000); 
} 

function main(){ 
    for(var j=0;j<lat1.length;j++){ 
    alert(locations1[j]+" has latitude of "+lat1[j]+", and longitude of 
    "+lon1[j]); 
    // do what ever else you want to do with the populated array 
    } 
} 

は、すべてのコードを持っているフィドルです:

http://jsfiddle.net/sharder14/afkzv2fx/

0

@AndrewEvtが正しい。投稿したコードの最後の2行の前にこれを追加してください: ... geocoder(); //これはジオコーダー関数を呼び出します
alert(lat [0]);
アラート(long [0]);

+0

すばらしい応答をありがとう!それでもまだ動作していません。どうやらそれは非同期です。また、elseステートメントの直後にアラートを置くと、アラートは機能しますが、ジオコードブロックの外側にはアクセスできません。 –

関連する問題