我正在尝试创建一个功能来有效地返回一个基于陆地的坐标数组。我已经使用Google的地理编码器有效地创建了一次性陆基坐标,但是我希望将它集成到一个系统中,通过使用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);
}
答案 0 :(得分:1)
当你执行'//调用地理编码器功能来检查坐标是否是基于陆地的'功能时,代码似乎正在崩溃。
错误:
Error: useless setTimeout call (missing quotes around argument?)
}), 250);
现在没有时间调试,但这里有一个我过去成功使用的样本,看起来更简单:
if (status == google.maps.GeocoderStatus.OK) { // -- Has a result been returned ?
DO process stuff
}else{ // -- Location not returned - must be in the sea !
DO in the sea stuff
}
可能会有所帮助吗?
答案 1 :(得分:1)
试试这个:
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);
}
}
});
}