我对 Google Maps DirectionsService 有奇怪的问题。如果输入数据相同,它会返回不同的路线。这是我的代码示例
var path = [];
path.push(new google.maps.LatLng(51.10600101811778, 17.025117874145508));
path.push(new google.maps.LatLng(51.1047951799623,17.02278971672058));
path.push(new google.maps.LatLng(51.10456276619924, 17.02208161354065));
path.push(new google.maps.LatLng(51.10131895649719, 17.029248476028442));
path.push(new google.maps.LatLng(51.100331957810134, 17.033969163894653));
path.push(new google.maps.LatLng(51.10001867395775, 17.032413482666016));
for (var i = 0; i <path.length-1; i++) {
var request = {
origin: path[i],
destination: path[i+1],
travelMode: google.maps.DirectionsTravelMode.WALKING
}
directionsService.route(request, function(results, status) {
if (status == google.maps.DirectionsStatus.OK) {
selected_path = selected_path.concat(results.routes[0].overview_path);
poly.setPath(selected_path);
poly.setMap(map);
}
})
}
第一次调用后,一个函数绘制了一条奇怪的折线,它总是连接起点和终点:
第二次调用,函数运行良好,路线绘制正确:
这只是输入静态数据的示例。通常我使用矩阵和动态标记上的动态数据,但总是如此。首先,起点与终点相连+其他点之间的奇怪连接。第二个调用函数运行良好。你们中有人知道如何解决这个问题吗?
最佳答案
这只是一个猜测:我相信正在发生的事情是路径被无序连接,因为方向请求是异步的。 (数据不一定按顺序返回)。我在下面所做的是将方向的每条腿按顺序排列在一个数组中,然后将数组展平为一个连续的列表,并仅在正确数量的请求成功返回后才显示。
我无法重现你的曲折,所以我不知道这个答案是否真的能解决问题。
// count number of directions requests that returned successfully
var count = 0;
for (var i = 0; i <path.length-1; i++) {
var request = {
origin: path[i],
destination: path[i+1],
travelMode: google.maps.DirectionsTravelMode.WALKING
};
// introduce variable scope to preserve value of i
(function(i) {
directionsService.route(request, function(results, status) {
if (status == google.maps.DirectionsStatus.OK) {
selected_path[i] = results.routes[0].overview_path;
count++;
// draw path only if all segments are completed
if(count == path.length-1) {
//flatten selected_path into 1-d array
selected_path = Array.prototype.concat.apply([], selected_path);
poly.setPath(selected_path);
poly.setMap(map);
}
}
});
})(i);
}
关于javascript - 为什么 Google Maps DirectionsService 返回不同的路线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10674330/