【发布时间】:2014-06-08 04:20:09
【问题描述】:
我正在尝试在地图上的点之间绘制路径。我有一个 2 点数组(用于我的测试)。 我可以轻松地在地图上绘制它们,但方向服务似乎没有按预期工作。
这是我应该根据谷歌地图得到的:
但这就是我得到的:
这里是Jsfiddle。
这是我的测试代码:
var map = undefined;
function initialize()
{
var mapOptions = {
center: new google.maps.LatLng(-33.885026, 151.268316),
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoom: 14
};
map = new google.maps.Map(document.getElementById("map"), mapOptions);
}
jQuery(document).ready(function($)
{
initialize();
loadPaths(map);
});
function loadPaths(gmap)
{
var latlngbounds = new google.maps.LatLngBounds(),
infoWindow = new google.maps.InfoWindow(),
pathPoints = [],
index=0,
positions = [
{latitude: "-33.88914",longitude: "151.25673"},
{latitude: "-33.888",longitude: "151.2623"},
];
// The fix
positions.reverse();
$.each(positions, function(k, v) {
var myLatlng = new google.maps.LatLng(v.latitude, v.longitude);
pathPoints.push(myLatlng);
index++;
});
// Intialize the Path Array
var path = new google.maps.MVCArray();
// Intialise the Direction Service
var service = new google.maps.DirectionsService();
var iconSymbol = {
path: 'M 40 20 L 80 20 L 100 40 L 100 140 L 20 140 L 20 40 Z',
anchor: new google.maps.Point(60, 10),
scale: 0.15,
strokeColor: '#000000',
strokeWeight: 1,
fillColor: 'steelblue',
fillOpacity: 0.8,
};
// Set the Path Stroke Color
var poly = new google.maps.Polyline({
map: gmap,
strokeColor: '#dd0000',
icons: [{
icon: iconSymbol
}]
});
// Draw the path for this vehicle
// We compute the path between each point to follow the road
for (var i = 0; i < pathPoints.length; i++) {
// If it's not the last point
if ((i + 1) < pathPoints.length) {
var src = pathPoints[i];
var des = pathPoints[i + 1];
// We had the starting point to the poly path
path.push(src);
// We compute the path between the 2 points
service.route({
origin: src,
destination: des,
travelMode: google.maps.DirectionsTravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.IMPERIAL
}, function (result, status) {
if (status == google.maps.DirectionsStatus.OK) {
// We add the new computed points
for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
path.push(result.routes[0].overview_path[i]);
}
}
});
}
}
// Set the path of the polyline to draw it
poly.setPath(path);
}
更新
感谢@anto,我已经解决了路径问题
但是我还是时不时有一个问题,路径不是画在路上的。我认为这是服务回调函数的asynchronous 问题,但我不确定如何修复它。
如果我在 jsfiddle 中重新启动脚本,它会随机运行,但有时我会得到这种绘图:
更新 2
看起来使用递归函数可以修复大部分问题,除了我的最后一点没有画出来:http://jsfiddle.net/maxwell2022/wY32u/11/
【问题讨论】:
-
你确定那是双向街吗?出行模式 WALKING 返回较短的路径。
-
如果您在开始/停止中交换纬度/经度值,您将在 Google 地图站点获得相同的路径。
-
正确,我必须更新我的问题,因为我仍然有 3 分的问题。
-
我觉得我需要一个递归函数来获取完整路径才能绘制它?
标签: google-maps-api-3 google-polyline google-directions-api