陸上座標の配列を効果的に返す機能を作成しようとしています。Google のジオコーダーを使用して 1 回限りの陸上座標を効果的に作成しましたが、while ブロックを使用して最終的に陸上座標の配列が作成されるシステムに統合したいので、必要な時間まで関数が呼び出されます。ランドベースの座標の数が決定されます。以下は機能するはずですが、関数が呼び出されると、ページ (JSFiddle を使用) がクラッシュします。
ロケーションベースの座標が見つかるたびに数を減らす必要があり、見つからない場合は見つかるまで関数が呼び出されると信じているため、なぜこれが当てはまるのか途方に暮れています(これは将来のある時点で)。
任意のガイダンスをいただければ幸いです。パブリック フィドルはhttp://jsfiddle.net/grabbeh/sajfb/にあります。
var map;
var coords = [];
var geocoder = new google.maps.Geocoder();
window.onload = function () {
center = new google.maps.LatLng(40.717, -74.006);
var options = {
zoom: 1,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'), options);
//randomLandBasedCoords(2, function(coords){
// addMarkersToMap(coords);
//});
};
function addMarkersToMap(places) {
for (var i = 0, j = places.length; i < j; i++) {
placeMarker(places[i]);
};
};
function placeMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map,
flat: true,
});
};
function randomLandBasedCoords(number, fn) {
if (number > 0) {
while (number > 0) {
// create random coordinate
var lng = (Math.random() * 360 - 180);
var lat = (Math.random() * 180 - 90);
var randomCoordinate = new google.maps.LatLng(lat, lng);
// call geocoder function to check if coordinate is land-based with a timeout to control flow (maybe)
setTimeout(geocoder.geocode({
location: randomCoordinate
}, function (results, status) {
if (status == "OK" && results) {
var landCoordinate = randomCoordinate;
coords.push(landCoordinate);
number--;
}
}), 250);
}
}
return fn(coords);
}