gpt4 book ai didi

javascript - 根据谷歌地图上的驾驶位置过滤地址

转载 作者:行者123 更新时间:2023-11-29 22:30:42 25 4
gpt4 key购买 nike

我正在尝试根据驾驶/步行时间过滤掉 Google map 上的地址。但是,似乎我遗漏了有关此 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) 我无法从内部访问变量“地址”:directionsService.route(request, function(response, status) {//.....这里.....});

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])
});

关于javascript - 根据谷歌地图上的驾驶位置过滤地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7060821/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com