gpt4 book ai didi

javascript - 使用地理编码返回陆基坐标数组的问题

转载 作者:行者123 更新时间:2023-11-29 22:08:34 25 4
gpt4 key购买 nike

我正在尝试创建一个功能来有效地返回一组基于陆地的坐标。我已经使用谷歌的地理编码器有效地创建了一次性的基于陆地的坐标,但是我想将它集成到一个系统中,最终通过使用一个 while block 创建一组基于陆地的坐标,所以该函数被调用直到必要的确定了陆基坐标的数量。我认为下面应该工作但是,当调用该函数时,页面(使用 JSFiddle)崩溃。

我不知道为什么会这样,因为我认为每次找到基于位置的坐标时都应该减少数量,如果找不到,将调用函数直到找到(这应该是在未来的某个时候)。

任何指导将不胜感激。公共(public) fiddle 位于 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);
}

最佳答案

试试这个:

function randomLandBasedCoords(number,fn) {
// 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
geocoder.geocode({
location: randomCoordinate
}, function (results, status) {
if (status == "ZERO_RESULTS") {
randomLandBasedCoords(number,fn);
} else if (status == "OK" && results) {
var landCoordinate = randomCoordinate;
coords.push(landCoordinate);
if (coords.length < number) {
randomLandBasedCoords(number,fn);
} else {
return fn(coords);
}
}
});
}

关于javascript - 使用地理编码返回陆基坐标数组的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19568449/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com