angular fullcalendar loading time - mysql

I'm currently using "FullCalendar" for angular JS. Although it works fine, it takes around 15 seconds to load the calendar even though the data it coming from the php file instantly, does anyone have experience with fullcalendar and could help me optimize my script or see where I may be going wrong? Here is my calendar function :
$scope.refreshCal = function() {
$scope.colors = [];
var getAppointmentsurl = './dbscripts/getAppointments.php';
$http({ method: 'GET', url: getAppointmentsurl }).success(function(data) {
$scope.apnts = data;
angular.forEach(data, function(item, key) {
if ($scope.inArray(item.username)) {
$scope.colors.push(item.colorcode);
$scope.consultantsApps = data;
var appdate = new Date(moment(item.Appointment).format("YYYY-MM-DD"));
var appdatee = moment(item.Appointment, "YYYY-MM-DD");
var newtime = moment(item.txtTime).format("hh:mm a");
var time = newtime;
var hours = Number(time.match(/^(\d+)/)[1]);
var minutes = Number(time.match(/:(\d+)/)[1]);
var AMPM = time.match(/\s(.*)$/)[1];
if (AMPM == "pm" && hours < 12) hours = hours + 12;
if (AMPM == "am" && hours == 12) hours = hours - 12;
var sHours = hours.toString();
var sMinutes = minutes.toString();
if (hours < 10) sHours = "0" + sHours;
if (minutes < 10) sMinutes = "0" + sMinutes;
var y = appdatee.get("year");
var m = appdatee.get("month");
var d = appdatee.get("date");
var h = sHours;
var min = sMinutes;
var info = item.Company + ", " + item.Town + ", " + item.PostCode;
// var event= {title: item.Ref,color:item.colorcode,start: new Date(apnt.get("year"), apnt.get("month"), apnt.get("date"), t.get('hour'), t.get('minute')),end: new Date(apnt.get("year"), apnt.get("month"), apnt.get("date"), t.get('hour') + 1, t.get('minute')),allDay: false}
var event = {
ref: item.Ref,
cons: item.username,
title: (info),
color: item.colorcode,
start: new Date(y, m, d, h, min),
end: new Date(y, m, d, h, min),
allDay: false
};
$scope.events.push(event);
}
$scope.eventSources = [$scope.events];
})
});
};
Most of it is just formatting dates and times but other than that it's just looping through the list of appointments, adding them to $scope.events and pushing it to the calendar.
Thanks for your help!

Related

How to create Calendar Events to generate notifications for taking medications

I like to create calendar events with notifications to assist me in taking medications sometimes when the medication regimen gets complicated. I found this application to be quite useful to me and thought perhaps others might like to use such a script. It uses an array of objects to process the medication title, the hours it must be taken and the notifications that you require.
Admittedly, I used hours only rather than hours and minutes. It seemed like a useful simplification to me.
Here's the code:
function createMyEvents() {
const cal = CalendarApp.getCalendarById("calendar id");
const tA = [{ title: "Take Med1", hours: [6, 12, 18, 23], nots: [10, 30] }, { title: "Take Med2", hours: [8, 20], nots: [10, 30] }];
//add to calendar for the following offset days
[2, 3, 4, 5, 6].forEach(offset => {
let dt = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate() + offset);
tA.forEach(obj => {
//using the hours array to create events for each day
obj.hours.forEach(h => {
let st = new Date(dt.getFullYear(), dt.getMonth(), dt.getDate(), h)
let et = new Date(dt.getFullYear(), dt.getMonth(), dt.getDate(), h + 1);
let event = cal.createEvent(obj.title, st, et)
obj.nots.forEach(m => {
event.addPopupReminder(m);//notifications for each event
});
});
});
});
}
My Current Answer:
Uses a control sheet to set up the parameters for each event creation sequence which also stores the event id's created which makes it possible to also delete the events by iterating through the list.
Code:
function makeEventArray(start = 9, end = 12, offA = '') {
if (!offA) {
const arr = [...Array.from(new Array(end - start + 1).keys(), x => start + x)];
//Logger.log(arr);
return arr;
} else {
return offA;
}
}
function createMyEventsFromList() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName('MakeEvents');
const shsr = 3;
let d = new Date();
sh.getRange("C1").setValue(d).setNumberFormat("MMM dd yyyy");
sh.getRange("E1").setValue(d).setNumberFormat("HH:mm:ss");
const vs = sh.getRange(shsr, 1, sh.getLastRow() - shsr + 1, sh.getLastColumn()).getValues().map((r,i) => {r[9] = i + shsr;return r; }).filter(r => r[0] == true).filter(e => e);
if (vs && vs.length > 0) {
ss.toast('Process Running','Creating Events',300)
vs.forEach(r => {
let idA = [];
let title = r[1];
let hours;
if (~r[2].toString().indexOf(',')) {
hours = r[2].toString().split(',').map(e => Number(e));
} else {
hours = [r[2]];
}
let nots;
if (~r[3].toString().indexOf(",")) {
nots = r[3].toString().split(',').map(e => Number(e));
} else {
nots = [r[3]];
}
let desc = r[4];
let start = r[5];
let end = r[6];
let offA;
if (r[7] && r[7].toString().length > 0) {
if (r[7].toString().includes(',')) {
offA = r[7].toString().split(',').map(e => Number(e));
} else {
offA = [r[7]];
}
}
const cal = CalendarApp.getCalendarById("q289qp9augtnshkn70dkibcc54#group.calendar.google.com");
const tob = { start: start, end: end, offA: offA, desc: desc, tA: [{ title: title, hours: hours, nots: nots }] };
makeEventArray(tob.start, tob.end, tob.offA).forEach(offset => {
let dt = new Date(d.getFullYear(), d.getMonth(), d.getDate() + offset);
tob.tA.forEach(obj => {
obj.hours.forEach(h => {
let st = new Date(dt.getFullYear(), dt.getMonth(), dt.getDate(), h)
let et = new Date(dt.getFullYear(), dt.getMonth(), dt.getDate(), h + 1);
let event = cal.createEvent(obj.title, st, et);;
if (event) {
event.setDescription(tob.desc);
idA.push(event.getId())
}
if (event && obj.nots && obj.nots.length > 0) {
obj.nots.forEach(m => {
event.addPopupReminder(m);
});
}
});
});
});
sh.getRange(r[9],9,1,2).setValues([[idA.join(', '),r[9]]])
});
ss.toast('Process Complete','Creating Events',15);
}
}
function deleteEventsFromList() {
const cal = CalendarApp.getCalendarById("q289qp9augtnshkn70dkibcc54#group.calendar.google.com");
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName('MakeEvents');
const shsr = 3;
const vs = sh.getRange(shsr, 1, sh.getLastRow() - shsr + 1, sh.getLastColumn()).getValues().map((r,i) => {r[9] = i + shsr;return r; }).filter(r => r[0] == true).filter(e => e);
ss.toast('Process Running','Deleeting Events',180)
vs.forEach(r => {
r[8].toString().split(', ').forEach(id => {
cal.getEventById(id).deleteEvent();
});
sh.getRange(r[9],9,1,2).clearContent();
});
ss.toast('Process Complete','Deleeting Events');
}
Image of Sheet:
Changed
const shsr = 3;
let d = new Date();
to this to allow starting date selection:
const shsr = 3;
const r = SpreadsheetApp.getUi().prompt("Get StartDate","yyyy/M/d",SpreadsheetApp.getUi().ButtonSet.OK_CANCEL);
if(r.getSelectedButton() == SpreadsheetApp.getUi().Button.OK) {
var t = r.getResponseText().split('/');
} else {
ss.toast("Making Events","Cancelled Operation by User",5)
return;
}
let d = new Date(t[0],Number(t[1]) - 1,t[2]);

Funky IE JSON conversions

When running our AngularJS app in IE11 everything looks great in the debugger, but when our app encodes the data as JSON to save to our database, we get bad results.
Our app obtains a record from our database, then some manipulation is done and then the data is saved back to the server from another model.
Here is the data I got back from the server in the setAttendanceGetSInfo() function below:
{"data":{"Start":"2014-10-16T19:36:00Z","End":"2014-10-16T19:37:00Z"},
This is the code used to "convert the data" to 3 properties in our model:
var setAttendanceGetSInfo = function (CourseId, PID) {
return setAttendanceInfo(CourseId, PID)
.then(function (result) {
return $q.all([
$http.get("../api/Axtra/getSInfo/" + model.event.Id),
$http.get("../api/Axtra/GetStartAndEndDateTime/" + aRow.Rid)
]);
}).then(function (result) {
var r = result.data;
var e = Date.fromISO(r.Start);
var f = Date.fromISO(r.End);
angular.extend(model.event, {
examDate: new Date(e).toLocaleDateString(),
examStartTime: (new Date(e)).toLocaleTimeString(),
examEndTime: (new Date(f)).toLocaleTimeString()
});
return result.sInfo;
});
};
fromISO is defined as:
(function(){
var D= new Date('2011-06-02T09:34:29+02:00');
if(!D || +D!== 1307000069000){
Date.fromISO= function(s){
var day, tz,
rx=/^(\d{4}\-\d\d\-\d\d([tT ][\d:\.]*)?)([zZ]|([+\-])(\d\d):(\d\d))?$/,
p= rx.exec(s) || [];
if(p[1]){
day= p[1].split(/\D/);
for(var i= 0, L= day.length; i<L; i++){
day[i]= parseInt(day[i], 10) || 0;
};
day[1]-= 1;
day= new Date(Date.UTC.apply(Date, day));
if(!day.getDate()) return NaN;
if(p[5]){
tz= (parseInt(p[5], 10)*60);
if(p[6]) tz+= parseInt(p[6], 10);
if(p[4]== '+') tz*= -1;
if(tz) day.setUTCMinutes(day.getUTCMinutes()+ tz);
}
return day;
}
return NaN;
}
}
else{
Date.fromISO= function(s){
return new Date(s);
}
}
})()
Take a look at the screenshot of the event model data:
But, if I eval the event model using JSON.stringify(model.event), I get this:
{\"examDate\":\"?10?/?16?/?2014\",\"examStartTime\":\"?2?:?44?:?00? ?PM\",\"examEndTime\":\"?2?:?44?:?00? ?PM\"}
And this is the JSON encoded data that actually got stored on the DB:
"examDate":"¿10¿/¿16¿/¿2014","examStartTime":"¿2¿:¿36¿:¿00¿ ¿PM","examEndTime":"¿2¿:¿37¿:¿00¿ ¿PM"
What is wrong here and how can I fix this? It works exactly as designed in Chrome and Firefox. I have not yet tested on Safari or earlier versions of IE.
The toJSON for the date class isn't defined perfectly the same for all browsers.
(You can see a related question here: Discrepancy in JSON.stringify of date values in different browsers
I would suspect that you have a custom toJSON added to the Date prototype since your date string doesn't match the standard and that is likely where your issue is. Alternatively, you can use the Date toJSON recommended in the above post to solve your issues.
First, I modified the fromISO prototype to this:
(function () {
var D = new Date('2011-06-02T09:34:29+02:00');
if (!D || +D !== 1307000069000) {
Date.fromISO = function (s) {
var D, M = [], hm, min = 0, d2,
Rx = /([\d:]+)(\.\d+)?(Z|(([+\-])(\d\d):(\d\d))?)?$/;
D = s.substring(0, 10).split('-');
if (s.length > 11) {
M = s.substring(11).match(Rx) || [];
if (M[1]) D = D.concat(M[1].split(':'));
if (M[2]) D.push(Math.round(M[2] * 1000));// msec
}
for (var i = 0, L = D.length; i < L; i++) {
D[i] = parseInt(D[i], 10);
}
D[1] -= 1;
while (D.length < 6) D.push(0);
if (M[4]) {
min = parseInt(M[6]) * 60 + parseInt(M[7], 10);// timezone not UTC
if (M[5] == '+') min *= -1;
}
try {
d2 = Date.fromUTCArray(D);
if (min) d2.setUTCMinutes(d2.getUTCMinutes() + min);
}
catch (er) {
// bad input
}
return d2;
}
}
else {
Date.fromISO = function (s) {
return new Date(s);
}
}
Date.fromUTCArray = function (A) {
var D = new Date;
while (A.length < 7) A.push(0);
var T = A.splice(3, A.length);
D.setUTCFullYear.apply(D, A);
D.setUTCHours.apply(D, T);
return D;
}
Date.toJSON = function (key) {
return isFinite(this.valueOf()) ?
this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z' : null;
};
})()
Then I added moment.js and formatted the dates when they get stored:
var SaveAffRow = function () {
// make sure dates on coursedate and event are correct.
var cd = model.a.courseDate;
var ed = model.event.examDate;
var est = model.event.examStartTime;
var eet = model.event.examEndTime;
model.a.courseDate = moment(cd).format("MM/DD/YYYY");
model.event.examDate = moment(ed).format("MM/DD/YYYY");
model.event.examStartTime = moment(est).format("MM/DD/YYYY hh:mm A");
model.event.examEndTime = moment(eet).format("MM/DD/YYYY hh:mm A");
affRow.DocumentsJson = angular.toJson({a: model.a, event: model.event});
var aff = {};
if (affRow.Id != 0)
aff = affRow.$update({ Id: affRow.Id });
else
aff = affRow.$save({ Id: affRow.Id });
return aff;
};
and when they get read (just in case they are messed up already):
var setAttendanceGetSInfo = function (CourseId, PID) {
return setAttendanceInfo(CourseId, PID)
.then(function (result) {
return $q.all([
$http.get("../api/Axtra/getSInfo/" + model.event.Id),
$http.get("../api/Axtra/GetStartAndEndDateTime/" + aRow.Rid)
]);
}).then(function (result) {
var r = result.data;
var e = Date.fromISO(r.Start);
var f = Date.fromISO(r.End);
angular.extend(model.event, {
examDate: moment(e).format("MM/DD/YYYY"),
examStartTime: moment(e).format("MM/DD/YYYY hh:mm A"),
examEndTime: moment(f).format("MM/DD/YYYY hh:mm A")
});
return result.sInfo;
});
};

Progressbar in angular

I want to make Progressbar in Angular.js in decimal format, simple format, times based Progressbar. Someone could pls help !
E.g.
Start Timer {{ counter }}/{{ max }} = {{ (counter/max)*100 }}%
Start Timer 20/30 = 66.66666666666666%
Here is example.js:
angular.module('plunker', ['ui.bootstrap']);
var ProgressDemoCtrl = function ($scope) {
$scope.max = 200;
$scope.random = function () {
var value = Math.floor((Math.random() * 100) + 1);
var type;
if (value < 25) {
type = 'success';
} else if (value < 50) {
type = 'info';
} else if (value < 75) {
type = 'warning';
} else {
type = 'danger';
}
$scope.showWarning = (type === 'danger' || type === 'warning');
$scope.dynamic = value;
$scope.type = type;
};
var app = angular.module('plunker', ['ui.bootstrap']);
app.controller('ProgressDemoCtrl', function ($scope) {
$scope.value = 40;
$scope.state = "progress-bar-success";
$scope.myStyle = {width: $scope.value + '%'};
});
$scope.random();
$scope.randomStacked = function() { $scope.stacked = [];
var types = ['success', 'info', 'warning', 'danger']; for (var i = 0, n = Math.floor((Math.random() * 4) + 1); i < n; i++) { var index = Math.floor((Math.random() * 4));
$scope.stacked.push({ value: Math.floor((Math.random() * 30) + 1),
type: types[index] }); } }; $scope.randomStacked(); };
var app = angular.module('progressApp',['nprogress']); var MainCtrl = function($scope,ngProgress){ }
I use this round progress ba directive, works pretty well:
http://www.youtube.com/watch?v=w2qrYL0Le24
https://github.com/angular-directives/angular-round-progress-directive
If you need a rectangular one give me a buzz I, have a custom directive implemented.
If you need two decimal numbers you only have to adjust the font size.
Test with two decimals:
Code to change (configuring ang:roundprogress directive)
data-round-progress-label-font="80pt Arial"
Whole markup
<div ang:round:progress data-round-progress-model="roundProgressData"
data-round-progress-width="500"
data-round-progress-height="500"
data-round-progress-outer-circle-width="40"
data-round-progress-inner-circle-width="10"
data-round-progress-outer-circle-radius="200"
data-round-progress-inner-circle-radius="140"
data-round-progress-label-font="80pt Arial"
data-round-progress-outer-circle-background-color="#505769"
data-round-progress-outer-circle-foreground-color="#12eeb9"
data-round-progress-inner-circle-color="#505769"
data-round-progress-label-color="#fff"></div>

Google Apps Script: Server encountered an error. Try again later

I am stuck.. Error is thrown # Line 63 and sometimes at line 50. Both using the appendTableRow() method. I can't find anything wrong.
row3.appendTableCell(entryDesc)
Link to generated file: Link
Execution Transcript: Link
I am new so if you notice any "bad practices" feel free to aim a finger.
// Import data from the Calendar to the timesheet document
function importDataToTS (dateStart,dateFinish,doc) {
if (!dateStart) {
var dateStart = new Date('January 1, 2014');
}
var cal = CalendarApp.getCalendarById('0k2s9lfibn50scj41gcuurovck#group.calendar.google.com')
var events = cal.getEvents(dateStart, dateFinish);
var oldDate = new Date(dateStart.getFullYear(), dateStart.getMonth(), dateStart.getDate() - 1);
var paragraph = "";
var totalHoursWorked = 0
// START --- Text element styles
// Date
var entryDateStyle = {};
entryDateStyle[DocumentApp.Attribute.BOLD] = true;
entryDateStyle[DocumentApp.Attribute.FONT_SIZE] = 18;
// Title
var entryTitleStyle = {};
entryTitleStyle[DocumentApp.Attribute.FONT_SIZE] = 14;
// entryTimes
var entryTimesStyle = {};
entryTimesStyle[DocumentApp.Attribute.BOLD] = true;
entryTimesStyle[DocumentApp.Attribute.FONT_SIZE] = 12;
// entryDescription
var entryDescriptionStyle = {};
entryDescriptionStyle[DocumentApp.Attribute.ITALIC] = true;
entryDescriptionStyle[DocumentApp.Attribute.FONT_SIZE] = 10;
// END --- Text element styles
var entriesTable = doc.appendTable();
Logger.log(entriesTable.getType());
for (var i = 0; i in events; i++) {
var entryDate = events[i].getStartTime();
if (i > 0) {
oldDate = (events[i-1].getStartTime());
}
// If it's a new day add a full width cell
if (entryDate.getDate() > oldDate.getDate()) {
var row1 = entriesTable.appendTableRow();
row1.appendTableCell(shortDate(entryDate,4));
//.setAttributes(entryDateStyle);
}
// Add title, start/end times & hours worked
// Add title, start/end times & hours worked
var entryTitle = events[i].getTitle();
Logger.log(i + ": " + entryTitle);
var entryTimes = shortTime(events[i].getStartTime(),2) + " - " + shortTime(events[i].getEndTime(),2);
Logger.log(i + ": " + entryTimes);
var entryHoursWorked = ((events[i].getEndTime() - events[i].getStartTime())/(1000*60*60)%24) + "hr(s)";
Logger.log(i + ": " + entryHoursWorked);
var row2 = entriesTable.appendTableRow();
row2.appendTableCell(entryTitle);
//.setAttributes(entryTitleStyle);
row2.appendTableCell(entryTimes + "\t\t" + entryHoursWorked);
//.setAttributes(entryTimesStyle);
// Add entry description
var entryDesc = (events[i].getDescription().length > 1) ? events[i].getDescription().toString() : "";
if (entryDesc.length > 1) {
var row3 = entriesTable.appendTableRow();
row3.appendTableCell();
row3.appendTableCell(entryDesc);
//.setAttributes(entryDescriptionStyle);
}
totalHoursWorked += entryHoursWorked;
if (i === (events.length - 1)) {
var lastRow = entriesTable.appendTableRow();
lastRow.appendTableCell("Total Hours: " + totalHoursWorked);
}
}
for (var i = 0; i in entriesTable; i++) {
for (var j = 0; j in entriesTable[i]; j++) {
Logger.log(i + ":" + j + " " + entriesTable[i][j].toString());
}
}
doc.appendTable(entriesTable);
}
shortDate() && shorttTime()
function shortDate(date,n) {
// Returns a date object as "MMMDD";
if (date) {
switch (n) {
case 1:
//Jul6
return Utilities.formatDate(date, "EST", "MMMdd")
break;
case 2:
//Jul 6
return Utilities.formatDate(date, "EST", "MMM dd")
break;
case 3:
//July 6
return Utilities.formatDate(date, "EST", "MMMM dd")
break;
case 4:
return Utilities.formatDate(date, "EST", "EEE, MMM dd")
break;
default:
//Full Date unchanged
return date;
}
}
}
function shortTime(date) {
//Returns time string formatted as "hh:mm"am/pm
//Still needs to be updated with Utilities.formatDate
if (date) {
var hours = (date.getHours() > 12) ? (date.getHours() - 12) : date.getHours();
var ampm = (date.getHours() > 12) ? "pm" : "am";
var minutes = (date.getMinutes() == 0) ? "00" : date.getMinutes();
var time = hours + ":" + minutes + ampm
return time.toString();
}
}
I found a solution, it appears that: body.appendTableCell(); doesn't handle line breaks "\n". When the script was importing a multi-line event description from the calendar I would get a "server error" message. Adding split('\n') to the description row solved the problem. This worked: body.appendTableCell(data).split("\n");
Finished code:
var entryDesc = (events[i].getDescription().length > 1) ? events[i].getDescription() : "";
if (entryDesc) {
var row3 = entriesTable.appendTableRow();
row3.appendTableCell("");
row3.appendTableCell(entryDesc.split("\n"))
.setAttributes(entryDescriptionStyle);
}
I don't have a complete answer but I thought it might be interesting in the mean time to show a version that works without the event description.
I changed the calculation of total time that didn't work either.
Code can be tested on any default calendar using test function.
function test(){
//dateStart,dateFinish,doc
var doc = DocumentApp.getActiveDocument();
var dateStart = new Date('January 1, 2014');
var dateFinish = new Date('April 1, 2014')
importDataToTS (dateStart,dateFinish,doc);
}
function importDataToTS (dateStart,dateFinish,doc) {
if (!dateStart) {
var dateStart = new Date('January 1, 2014');
}
var cal = CalendarApp.getDefaultCalendar();
var events = cal.getEvents(dateStart, dateFinish);
var oldDate = new Date(dateStart.getFullYear(), dateStart.getMonth(), dateStart.getDate() - 1);
var paragraph = "";
var totalHoursWorked = 0
// START --- Text element styles
// Date
var entryDateStyle = {};
entryDateStyle[DocumentApp.Attribute.BOLD] = true;
entryDateStyle[DocumentApp.Attribute.FONT_SIZE] = 18;
// Title
var entryTitleStyle = {};
entryTitleStyle[DocumentApp.Attribute.FONT_SIZE] = 14;
// entryTimes
var entryTimesStyle = {};
entryTimesStyle[DocumentApp.Attribute.BOLD] = true;
entryTimesStyle[DocumentApp.Attribute.FONT_SIZE] = 12;
// entryDescription
var entryDescriptionStyle = {};
entryDescriptionStyle[DocumentApp.Attribute.ITALIC] = true;
entryDescriptionStyle[DocumentApp.Attribute.FONT_SIZE] = 10;
// END --- Text element styles
var entriesTable = doc.appendTable();
Logger.log('events.length = '+events.length);
for (var i = 0; i <events.length; i++) {
var entryDate = events[i].getStartTime();
if (i > 0) {
oldDate = (events[i-1].getStartTime());
}
Logger.log('i = '+i);
// If it's a new day add a full width cell
if (entryDate.getDate() > oldDate.getDate()) {
var row1 = entriesTable.appendTableRow();
row1.appendTableCell(shortDate(entryDate,4))
.setAttributes(entryDateStyle);
}
// Add title, start/end times & hours worked
var entryTitle = events[i].getTitle();
var entryTimes = shortTime(events[i].getStartTime(),2) + " - " + shortTime(events[i].getEndTime(),2);
var entryHoursWorked = (events[i].getEndTime().getTime() - events[i].getStartTime().getTime())/(1000*60*60) + "hr(s)";
var row2 = entriesTable.appendTableRow();
row2.appendTableCell(entryTitle)
.setAttributes(entryTitleStyle);
row2.appendTableCell(entryTimes + "\t\t" + entryHoursWorked)
.setAttributes(entryTimesStyle);
// Add entry description
var entryDesc = (events[i].getDescription().length > 2) ? events[i].getDescription() : "";
totalHoursWorked += Number(entryHoursWorked.replace(/\D/g,''));
if (i === (events.length - 1)) {
var lastRow = entriesTable.appendTableRow();
lastRow.appendTableCell("Total Hours: " + totalHoursWorked+' Hours');
}
}
for (var i = 0; i in entriesTable; i++) {
for (var j = 0; j in entriesTable[i]; j++) {
Logger.log(i + ":" + j + " " + entriesTable[i][j].toString());
}
}
doc.saveAndClose();
}

set depart and arrival time in google transit Api

I am currently working on one travel domain where I need to integrate "Trip Planner" using "Google Transit API V3". I am done with setting up map and all required option for trip planner. But here I am facing on problem.
I want to set "arrival_time" and "departure_time" in "TransitDetails" object in google API. I have created an object which returns me transit details on the route. But not as per "Departure" and "Arrival" Option passed in object.
This is what I have done in code
var directions = new google.maps.DirectionsService();
var renderer = new google.maps.DirectionsRenderer();
var startLocationAutocomplete;
var endLocationAutocomplete;
var map, transitLayer;
function initialize() {
var mapOptions = {
zoom:14,
center:new google.maps.LatLng(51.538551, -0.016633),
mapTypeId:google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'), mapOptions);
google.maps.event.addDomListener(document.getElementById('go'), 'click', route);
var defaultBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(35.371359, -79.319916),
new google.maps.LatLng(36.231424, -77.752991));
var autocompleteOptions = {
bounds:defaultBounds,
types:[ "locality", "political", "geocode" ]
};
startLocationAutocomplete = new google.maps.places.Autocomplete(document.getElementById('from'));
endLocationAutocomplete = new google.maps.places.Autocomplete(document.getElementById('to'));
startLocationAutocomplete.bindTo('bounds', map);
endLocationAutocomplete.bindTo('bounds', map);
transitLayer = new google.maps.TransitLayer();
var control = document.getElementById('transit-wpr');
map.controls[google.maps.ControlPosition.TOP_RIGHT].push(control);
google.maps.event.addDomListener(control, 'click', function () {
transitLayer.setMap(transitLayer.getMap() ? null : map);
});
addDepart();
route();
}
function addDepart() {
var departHr = document.getElementById('departHr');
var departMin = document.getElementById('departMin');
for (var hr = 1; hr < 12; hr++) {
departHr.innerHTML += '<option value = "'+hr+'">' + hr + '</option>';
}
for (var i = 0; i < 12; i++) {
for (var j = 0; j < 60; j += 5) {
var x = i < 10 ? '0' + i : i;
var y = j < 10 ? '0' + j : j;
departMin.innerHTML += '<option value = "'+y+'">' + y + '</option>';
}
}
}
function formatAMPM() {
var date = new Date();
var hours = document.getElementById('departHr').value;
var minutes = document.getElementById('departMin').value;
var ampm = document.getElementById('timeFormat').value;
/*hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0' + minutes : minutes;*/
console.log(hours);
if(ampm == 'pm'){
hours = 12 + parseInt(hours); }
var strTime = hours + ':' + minutes;
return strTime;
}
function route() {
var startLocation = document.getElementById('from').value;
var endLocation = document.getElementById('to').value;
var selectedMode = document.getElementById('modeOfTransportation').value;
var departure = formatAMPM();
var bits = departure.split(':');
var now = new Date();
var tzOffset = (now.getTimezoneOffset() + 60) * 60 * 1000;
var time = ($('#travelDate').val() != '') ? new Date($('#travelDate').val()) : new Date();
time.setHours(bits[0]);
time.setMinutes(bits[1]);
var ms = time.getTime() - tzOffset;
var departureTime = time;
var request = {
origin:startLocation,
destination:endLocation,
travelMode:google.maps.TravelMode[selectedMode],
provideRouteAlternatives:true,
transitOptions:{
departureTime:departureTime
}
};
console.log(request);
var panel = document.getElementById('panel');
panel.innerHTML = '';
directions.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
renderer.setDirections(response);
renderer.setMap(map);
renderer.setPanel(panel);
console.log(status);
} else {
renderer.setPanel(null);
alert(status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
Can somebody help me out with any reference or any code hint to it correct.
Thanks
You need to do something like this
//TranDep and TranArr have a valid date or ''
if ((TranDep == '') && (TranArr == '')) var Transit = null;
else {
if ((TranDep != '') && (TranArr != ''))
var Transit = {arrivalTime: new Date(TranArr), departureTime: new Date(TranDep)}
else {
if ((TranDep == '') && (TranArr != ''))
var Transit = {arrivalTime: new Date(TranArr)}
else
var Transit = {departureTime: new Date(TranDep)}
}
}
var Dir = new google.maps.DirectionsService();
var request = {
transitOptions: Transit,
......... // the others properties
};
If you specifies a arrivalTime, the departureTime will be ignored.
Regards