为什么全局变量似乎不受内部范围(Javascript)的影响?

时间:2013-11-27 17:09:04

标签: javascript google-maps-api-3 scope

我正在尝试使用Google Map API计算从数据库到指定地址的最短坐标距离。问题不存在,我设法在找到一个更短的距离时提醒。但是名为“duration”的div将其innerHTML设置为初始值..

我不明白,我知道范围如何运作.. 我已经编了好几个小时了,也许我再也看不清了。     

var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
var shortestDistance= 99999999;
var myOptions = {
  zoom:7,
  mapTypeId: google.maps.MapTypeId.ROADMAP
}
var positions = new Array();
<?php
  while($row = mysqli_fetch_array($result)){
    echo'positions.push(['.$row['latitude'].','.$row['longitude'].']);';
  }
?>

for(var i=0;i<positions.length;i++){
  var originTemp = "";
  originTemp += positions[i][0] + "," + positions[i][1];
  var request = {
    origin: originTemp,
    destination: "1 Ste-Catherine St.",
    durationInTraffic: true,
    travelMode: google.maps.DirectionsTravelMode.DRIVING
   };

  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      var newRoute = response.routes[0].legs[0].duration.value;
      directionsDisplay.setDirections(response);
      if(newRoute<shortestDistance){
        shortestDistance=newRoute;
        alert("New shorter distance: "+shortestDistance);
      }
    }
  });
}
document.getElementById('duration').innerHTML += shortestDistance + " seconds";
</script>

3 个答案:

答案 0 :(得分:4)

你正在进行ajax调用。它们默认是异步的。

当来自该调用的响应进入并且您实际上进行“更短”比较时,JS代码块的其余部分(包括设置.innerHTML的位)已经执行,并设置距离至9999999。

答案 1 :(得分:1)

行车路线服务是异步的,在回调例程中检测到值时(运行时)设置值。

var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
var shortestDistance= 99999999;
var myOptions = {
  zoom:7,
  mapTypeId: google.maps.MapTypeId.ROADMAP
}
var positions = new Array();
<?php
  while($row = mysqli_fetch_array($result)){
    echo'positions.push(['.$row['latitude'].','.$row['longitude'].']);';
  }
?>

for(var i=0;i<positions.length;i++){
  var originTemp = "";
  originTemp += positions[i][0] + "," + positions[i][1];
  var request = {
    origin: originTemp,
    destination: "1 Ste-Catherine St.",
    durationInTraffic: true,
    travelMode: google.maps.DirectionsTravelMode.DRIVING
   };

  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      var newRoute = response.routes[0].legs[0].duration.value;
      directionsDisplay.setDirections(response);
      if(newRoute<shortestDistance){
        shortestDistance=newRoute;
        document.getElementById('duration').innerHTML += shortestDistance + " seconds";
        alert("New shorter distance: "+shortestDistance);
      }
    }
  });
}
</script>

答案 2 :(得分:0)

尝试在找到新的shortestDistance时分配div的内容:

  if(newRoute<shortestDistance){
    shortestDistance=newRoute;
    alert("New shorter distance: "+shortestDistance);
    document.getElementById('duration').innerHTML = shortestDistance + " seconds";
  }