根据Google地图上的驾车位置过滤地址

时间:2011-08-15 00:55:04

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

我正在尝试根据驾驶/步行时间过滤掉Google地图上的地址。 但是,似乎我在这个Javascript代码段的运行方式中缺少一些非常基本的东西:

//addresses that I'd like to compare to a point of origin
var addresses = ['address_1','address_2','address_3','address_4','address_5'];
//point of interest/origin
var origin = 'origin_address';

for (i=0;i<addresses.length;i++){
  var directionsService = new google.maps.DirectionsService();
  var directionsDisplay = new google.maps.DirectionsRenderer();
  directionsDisplay.setMap(map);

  var request = {
    origin: origin, 
    destination: addresses[i],
    travelMode: google.maps.DirectionsTravelMode.DRIVING
    };

  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      //====> Why can't I access results[i] here? I get "undefined" for the following
      alert(addresses[i]);

      // I get 3 identical values, then a unique fourth value
      alert(response.routes[0].legs[0].duration.value);

      //if the duration is below a certain value, I'd like to show a marker.
      //however, I can't do that, since I can't access addresses[i]
      if(response.routes[0].legs[0].duration.value < 1200){
        //Geocode address & show marker
      }
    }
  });
}

知道原因: 1)我无法从内部访问变量“addresses”:directionsService.route(request,function(response,status){ //.....这里..... });

2)这是比较不同路线的持续时间的正确方法,还是我做的事情效率很低?

非常感谢!

1 个答案:

答案 0 :(得分:2)

该函数是一个回调函数。它的范围不同。你可能会怎么想。在那个功能中,我不存在。

我的手机对SO来说真的很糟糕,但你的响应变量会有你要求变量的地址。

修改

您可以尝试闭包:

directionsService.route(request, (function (address) {
    return function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      //====> Why can't I access results[i] here? I get "undefined" for the following
      alert(address);

      // I get 3 identical values, then a unique fourth value
      alert(response.routes[0].legs[0].duration.value);

      //if the duration is below a certain value, I'd like to show a marker.
      //however, I can't do that, since I can't access addresses[i]
      if(response.routes[0].legs[0].duration.value < 1200){
        //Geocode address & show marker
      }
    })(addresses[i])
  });