下面是我的简单代码,它获取从A点到B点(地址数组)的距离。问题在于“alert(end[i]+distanceKM);
”,尤其是变量distanceKM。
我认为我做对了。变量distanceKM在for循环之外声明,值在for循环中设置。我的警报在for循环中。
但我还是得到了
警报值:4700高速公路280未定义等等......
似乎distanceKM尚未设置,= undefined,我有:distanceKM = response.routes [0] .legs [0] .distance.value / 1000;
测试代码:
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<title>Distance Calculator</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
}
function calcRoute() {
var start = document.getElementById("start").value;
var end = document.getElementById("end").value.split('@@');
var distanceKM;
for (i = 0; i < end.length; i++)
{
var request = {
origin:start,
destination:end[i],
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status)
{
if (status == google.maps.DirectionsStatus.OK)
{
directionsDisplay.setDirections(response);
distanceKM=response.routes[0].legs[0].distance.value / 1000;
}
});
alert(end[i]+distanceKM);
}
}
</script>
</head>
<body onload="initialize()">
<div>
<p>
<label for="start">Start: </label>
<input type="text" name="start" id="start" value="815010 NE 36th Steet, Redmond, WA, USA" />
<label for="end">End: </label>
<input type="text" name="end" id="end" value="4700 Highway 280, Birmingham, AL, USA@@6900 US Highway 90, Suite 2, Daphne, AL, USA@@549 Brookwood Village, Homewood, AL, USA@@4800 Whitesburg Dr., Huntsville, AL, USA" />
<input type="submit" value="Calculate Route" onclick="calcRoute()" />
</p>
<p>
<label for="distance">Distance (km): </label>
<input type="text" name="distance" id="distance" readonly="true" />
</p>
</div>
</body>
</html>
答案 0 :(得分:0)
路由请求不会同步返回结果,因此如果您尝试在请求之外立即访问distanceKM,它仍然是未定义的。
为了帮助您了解执行顺序,请参阅编号注释:
// 1.) route request is sent, and the anonymous callback
// function is defined.
directionsService.route(request, function(response, status)
{
// 3.) Response from google is received and the anonymous
// callback function is called.
if (status == google.maps.DirectionsStatus.OK)
{
directionsDisplay.setDirections(response);
// 4.) distanceKM is set.
distanceKM=response.routes[0].legs[0].distance.value / 1000;
}
});
// 2.) Alert is shown
alert(end[i]+distanceKM);
因此,为了让您的提醒工作,请在distanceKM=... / 1000;
之后立即安排。您还需要对end [i]进行特殊处理。 e.g。
directionsService.route(request, (function(destination){
return function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
distanceKM=response.routes[0].legs[0].distance.value / 1000;
alert(destination+distanceKM);
}
};
})(request.destination));