Senario:
我有一个谷歌地图,它的一个功能是显示从中心点到同一地图上几个不同位置的路线信息。 我知道每个方向对象只能显示一组路线,所以我有一个函数,每次调用时都会创建一个渲染对象,并将路径放在地图上并为每个位置调用它。
代码:
计算和显示路线的功能:
function calculateRoot (startLocation,wayPoints,endLocation) {
var selectedMode = $("#travelMode").val();
// create a new directions service object to handle directions requests
var directionsService = new google.maps.DirectionsService();
// create a directions display to display route info on the map
var directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay.setMap(map);
// Stops the default googlemarkers from showing
directionsDisplay.suppressMarkers = true;
directionsDisplay.setPanel(document.getElementById("directions"));
// create a request object
var request = {
origin:startLocation,
waypoints: wayPoints,
destination:endLocation,
travelMode: google.maps.TravelMode[selectedMode],
optimizeWaypoints:true,
provideRouteAlternatives:true,
transitOptions: {
departureTime: new Date()
}
};
directionsService.route(request, function(result,status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
return directionsDisplay;
}
else if (status == google.maps.DirectionsStatus.ZERO_RESULTS){
alert ('No routing can be found for this Journey');
return -1;
}
else {
alert ('The following error occoured while attempting to obtain directions information:'+'\n'+status + '\n' + 'For:'+ ' '+ request.destination);
return -1;
}
});
}
所有位置功能:
function showAllRoutes(){
if ( ! directionsArray.length < 1) {
// if directions are already displayed clear the route info
clearRoots();
}
$('#directions').empty();
// craete an empty waypoint array just to pass to the function
var wayPoints = [];
for (var i = 0; i< markerArray.length; i++) {
var directions = calculateRoot(startLatLng,wayPoints,markerArray[i].position);
directionsArray.push(directions);
}
sizeMap();
$('#directions').show();
}
清除路线的功能
function clearRoutes() {
if (directionsArray.length <1 ) {
alert ("No directions have been set to clear");
return;
}
else {
$('#directions').hide();
for (var i = 0;i< directionsArray.length; i ++) {
if (directionsArray [i] !== -1) {
directionsArray [i].setMap(null);
}
}
directionsArray.clear();
map.setZoom(5);
return;
}
}
问题:
虽然无论我做什么,生成和显示路线似乎都能正常工作,但除非我刷新,否则我无法清除地图上的路线。 我错过了一些简单的东西,或者我不需要以这种方式做什么,我一直试图让这个工作超过一天,我很难过。 有人可以帮忙吗? 提前致谢
答案 0 :(得分:0)
Directions service是异步的,calculateRoot(或calculateRoute或其他任何它真正调用的)都不能返回任何内容,你需要将路由推送到回调函数中的全局数组中。
这是你的回调函数:
function(result,status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
return directionsDisplay;
}
将其更改为:
function(result,status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
directionsArray.push(directionsDisplay);
}