调用标记数组中最后一个标记之前的标记位置
Call the position of the marker before the last one in an array of markers
我想在自动完成的搜索输入的标记之间使用方向服务(google maps API V3(。我把标记放进了一个数组,但我无法得到最后一个(标记[i-1](之前标记的位置。
我只得到了这一个的"未捕获类型错误:无法读取未定义的属性'position'"。
完整代码:https://stackoverflow.com/questions/23365667/get-directions-from-one-place-to-another-from-input
为什么会发生这种情况?
for (var i = 0; i < markers.length; i++) {
if (markers.length > 1) {
place = markers[i].position;
console.log(place);
lastPlace = markers[i-1].position;
console.log(lastPlace);
calcRoute();
}
}
function calcRoute() {
var start = lastPlace;
var end = place;
console.log(start);
console.log(end);
var request = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
markers.length
(很可能(总是1或更大。因此,您将在每个第一个循环中得到错误,markers[0-1]
将始终未定义。使用
if (i > 0) {
place = markers[i].position;
console.log(place);
lastPlace = markers[i-1].position;
console.log(lastPlace);
calcRoute();
}
或
for (var i = markers.length; i>1; i--) {
place = markers[i].position;
console.log(place);
lastPlace = markers[i-1].position;
console.log(lastPlace);
calcRoute();
}
相反。
相关文章:
- 如何从某个位置顺时针和逆时针循环数组
- 将javascript数组中的项移动到特定位置的有效方法
- 生成ACF标记位置的数组(元素列表后缺少])
- 基于javascript中位置的数组差异
- Javascript删除数组中某个位置之后的项
- 在数组中迭代时的JS循环位置
- 在两个位置显示数组中的随机单词
- 放大位置数组
- Javascript 地理位置:将坐标存储在数组中
- 将地理位置坐标放入数组中
- 将地理编码器的位置保存到数组中
- 无法将所有位置值保存到我的数组中
- 如果用户靠近并触发特定事件,请检查位置数组
- 猫鼬位置数组更新
- 生成XSLT处理后的位置数组
- 如何在谷歌地图的位置数组中赋值
- 需要帮助合并2个位置数组和for循环
- 带有静态变量的地理位置数组
- 谷歌地图-从基于地图的位置数组中获取值'目前的观点
- 如何使用位置数组添加折线