我正在使用 google API v3 来绘制路线。我必须使用循环在地图上绘制许多路线,问题是由于函数调用是异步的,因此未绘制某些路线。当我在函数中添加“警报”时,它会起作用。所以为了解决这个问题,我写了一个“回调”函数,但它不起作用,知道如何纠正它吗?
function plotRoute()
{
var count = jsonObject[i].length-1;
var count1 = jsonObject[i].length;
var route_slipt = count1/7;
color = "#"+((1<<24)*Math.random()|0).toString(16);
var start_latlng = new google.maps.LatLng(start,end);
var end_latlng = new google.maps.LatLng(jsonObject[i][count].lat,jsonObject[i][count].lng);
var travelWaypoints = [];
for(var j in jsonObject[i]) {
travelWaypoints.push({location: new google.maps.LatLng(jsonObject[i][j].lat,jsonObject[i][j].lng),stopover:false});
}
//alert(travelWaypoints);
var request = {
origin : start_latlng,
destination : end_latlng,
waypoints :travelWaypoints,
travelMode : google.maps.DirectionsTravelMode.DRIVING
};
putRoute(request,color);
}
}
function putRoute(request,color,callback)
{
//alert('Route Plotted');
//setTimeout(function() {alert('hello');},1250);
var color = color;
var request = request;
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK)
{
var polylineOptionsActual = {
strokeColor :color,
strokeOpacity: 1.0,
strokeWeight : 5,
};
var directionsRenderer = new google.maps.DirectionsRenderer;
directionsRenderer.setMap(map);
directionsRenderer.setOptions( { polylineOptions: polylineOptionsActual, suppressMarkers: true} );
directionsRenderer.setDirections(response);
// directionsDisplay.setDirections(response);
if (typeof callback === "function") {
callback(request);
}
}
else
{
alert("Directions request failed:" + status);
}
});
}
putRoute(request,function() {
//alert('Finished eating my sandwich.');
});