我使用google api中的一个功能在地图上绘制一个方法,它可以很好地支持mehode:
calculateAndDisplayRoute(directionsService, directionsDisplay) {
var waypts = [];
// var jsonData = JSON.parse(this.city);
if (!this.isArrayEmpty(this.stations)) {
for (var i = 0; i < this.stations.length; i++) {
waypts.push({
location: this.stations[i].station,
stopover: true
});
}
}
directionsService.route({
origin: this.depart,
destination: this.arrivee,
waypoints: waypts,
optimizeWaypoints: false,
travelMode: 'DRIVING'
}, function (response, status) {
if (status === 'OK') {
directionsDisplay.setDirections(response);
var route = response.routes[0];
let momo;
// For each route, display summary information.
for (var i = 0; i < route.legs.length; i++) {
var routeSegment = i + 1;
alert('coco');
let dt = new Date(route.legs[i].duration.value*1000);
let hr = dt.getHours();
let m = "0" + dt.getMinutes();
let s = "0" + dt.getSeconds();
let durationn= hr+ ':' + m.substr(-2) + ':' + s.substr(-2); //this gives 02:35:45 for exemple
/*
//I tried this this code in comment but it doesnt work.
let time1=durationn;
momo=time1;
let [hours1, minutes1, seconds1] = time1.split(':');
let [hours2, minutes2, seconds2] = momo.split(':');
momo=moment({ hours: hours1, minutes: minutes1, seconds: seconds1 })
.add({ hours: hours2, minutes: minutes2, seconds: seconds2 })
.format('h:mm:ss')
*/
console.log('mm'+ route.legs[i].start_address + ' '+route.legs[i].end_address +' '+route.legs[i].distance.text+' '+route.legs[i].duration.text);
console.log( momo);
}
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
但我的问题在于持续时间,我会解释,我希望每次这个功能被调用,我需要持续时间被起诉(持续时间的总和)。 我在评论中尝试了这个代码,但它不起作用。 PS: 请不要浪费时间去理解代码,只关注第二个for loop block中的内容。
答案 0 :(得分:0)
你可以这样做:
var sum = {h: 0, m: 0, s: 0};
var allTimes = ["02:35:45", "11:40:30", "12:55:39"];
allTimes.forEach(time => sum = sumUp(sum, time)); // Just sum up hour, minute and second
console.log(parseSum(sum)); // Do formatting in the end
function sumUp(sum, time) {
var times = time.split(":");
sum.h += +times[0];
sum.m += +times[1];
sum.s += +times[2];
return sum;
}
function parseSum(sum) {
var totSec = sum.s;
var s = totSec % 60;
var totMin = sum.m + parseInt(totSec/60);
var m = totMin % 60;
var totHour = sum.h + parseInt(totMin/60);
var h = totHour;
return `${h}:${m}:${s}`;
}