在下面的代码中(观看错误控制台!)我正在快速查询谷歌地图的十个不同位置,以了解它是否可以计算到那里的路线。这确实有效,但我需要Google的结果在继续循环之前进入(在控制台中交替使用行,而不是现在我的循环遍历的地方,然后来自Google的状态)。
我该怎么做?
在用回调尝试了很长一段时间之后,我在这里学到了Google Maps V3 setDirections() callback我可能需要用事件监听器来做这件事。所以我尝试搜索API参考但是找不到任何接近的东西......但话又说回来,我是新手所以......任何想法?
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title></title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?"></script>
</head>
<body style="font-family: Arial; font-size: 12px; color:#FFFFFF;" bgcolor="#202020">
<div id="map" style="width: 300px; height: 300px;"></div>
<script type="text/javascript">
var counter = 0;
var destination_lat = 52.498775;
var destination_long = 13.518474;
do {
var destination_long = (destination_long + 0.2);
var destination = destination_lat + ", " + destination_long;
var finaldestination = destination.toString();
calcRoute();
console.error('longitude: ' + destination_long.toFixed (1) + ', counter: ' + counter);
counter = (counter + 1);
}
while (counter < 10);
function calcRoute() {
var directionsService = new google.maps.DirectionsService();
var request = {
origin: 'Potsdamer Platz, 10785 Berlin',
destination: finaldestination,
travelMode: google.maps.DirectionsTravelMode.TRANSIT,
};
directionsService.route(request, function(response, status) {
console.error('DirectionsStatus is ' + status);
});
}
</script>
</body>
</html>
答案 0 :(得分:0)
我认为我需要一个事件监听器,但是在他的评论中他的地理编码是正确的 - 我没有(并且我非常确定我还没有完全)理解异步性。
无论如何,下面的代码按预期工作 - 不知道这是一个很好的方法这样做但它确实有效(唯一的事情:我稍微改变它,所以它不总是进行十个查询,但只有查询只要有没有路线,一旦有一个就停止了):
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title></title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?"></script>
</head>
<body style="font-family: Arial; font-size: 12px; color:#FFFFFF;" bgcolor="#202020">
<script type="text/javascript">
var destination_lat = 53.5219216;
var destination_long = 13.4110207;
var finaldestination = 'lalala';
var valid_route = 1; // is set to 0 if route is valid, otherwise counts loops
mainLoop();
function mainLoop() {
if (valid_route >= 1) {
destination_long = (destination_long + 0.2);
finaldestination = (destination_lat + ", " + destination_long);
finaldestination = finaldestination.toString();
calcRoute();
console.error('longitude: ' + destination_long.toFixed (1) + ', loop count (valid_route): ' + valid_route);
}
}
function calcRoute() {
var directionsService = new google.maps.DirectionsService();
var request = {
origin: 'Potsdamer Platz, 10785 Berlin',
destination: finaldestination,
travelMode: google.maps.DirectionsTravelMode.TRANSIT,
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
valid_route = 0;
}
else {
valid_route = (valid_route + 1);
}
console.error('DirectionsStatus is ' + status);
mainLoop();
});
}
</script>
</body>
</html>