Mar*_*us0 2 javascript google-maps google-maps-api-3
我对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);
}
})
}
Run Code Online (Sandbox Code Playgroud)
调用后第一次,函数绘制一条奇怪的折线,始终将起点与终点连接起来:
第二次调用它时,该函数运行良好,并正确绘制路径:
它只是输入静态数据的一个例子.通常我使用矩阵和动态标记的动态数据,但总是一样.首先,起点与终点+其他点之间的奇怪连接相连.第二通电功能运行良好.你们中的某些人是否有一些线索如何解决这个问题?
这只是一个猜测:我相信正在发生的事情是路径变得无序连接,因为路线请求是异步的.(数据不一定按顺序返回).我在下面做的是将方向的每一条腿按顺序放在一个数组中,然后将数组展平成一个连续的列表,并且只有在正确数量的请求成功返回后才显示.
我无法重现你的曲折,所以我不知道这个答案是否真的能解决问题.
// 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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1900 次 |
| 最近记录: |