Cannot collect alle results of asynchronous call with geo.getLocations (Google Maps) - javascript

Below is my code. The problem is that recordsOut[0] is always undefined, whatever I try.
I know it has to do with the callback result. I tried to add some delays to give it more time to give a result back, but that did not help.
Any idea (with example please)? Very much appreciated.
function getAddress(id, searchValue) {
geo.getLocations(searchValue, function(result) {
if (result.Status.code == G_GEO_SUCCESS) {
var recordsOutStr = id + ';' + searchValue + ';';
for (var j = 0; j < result.Placemark.length; j++)
recordsOutStr += result.Placemark[j].address + ';' + result.Placemark[j].Point.coordinates[0] + ';' + result.Placemark[j].Point.coordinates[1];
recordsOut.push(recordsOutStr);
alert(recordsOutStr);
}
else {
var reason = "Code " + result.Status.code;
if (reasons[result.Status.code])
reason = reasons[result.Status.code]
alert('Could not find "' + searchValue + '" ' + reason);
}
});
}
function delay(ms)
{
var date = new Date();
var curDate = null;
do
{
curDate = new Date();
}
while (curDate - date < ms);
}
function processData()
{
objDataIn = document.getElementById("dataIn");
objDataOut = document.getElementById("dataOut");
if (objDataIn != null)
{
//alert(objDataIn.value);
if (objDataOut != null) {
recordsIn = explode(objDataIn.value, ';', true);
//for (i = 0; i < recordsIn.length; i++)
for (i = 0; i <= 5; i++)
{
addressStr = recordsIn[i]['address'] + ', ' +
recordsIn[i]['postalcode'] + ' ' +
recordsIn[i]['city'] + ', ' +
recordsIn[i]['country'];
getAddress(recordsIn[i]['id'], addressStr); //This will set resultStr
delay(200);
}
delay(5000);
alert('***' + recordsOut[0] + '***');
alert('***' + recordsOut[1] + '***');
alert('***' + recordsOut[2] + '***');
alert('***' + recordsOut[3] + '***');
alert('***' + recordsOut[4] + '***');
}
}
document.frmGeoCoder.submit();
}

Make sure that you have already defined recordsOut like this:
var recordsOut = [];
If you do it like this - var recordsOut; - it will be undefined.
If that doesn't work for you, please post the rest of the code, so we can see exactly what's going on.

Related

Google Ads scripts - how to do customised or long rolling date ranges

I'm using the following script to export Google Ads data from my account, but I am stuck with Google's pre-set date ranges and can't figure out how/if it's possible to jimmy these. Ideal date range would be year to date, with the report refreshing each day and adding on a fresh day's data, but would also be interested if we can get all time to work.
I'm a coding novice, so apologies in advance.
Script:
function main() {
var currentSetting = new Object();
currentSetting.ss = SPREADSHEET_URL;
// Read Settings Sheet
var settingsSheet = SpreadsheetApp.openByUrl(currentSetting.ss).getSheetByName(SETTINGS_SHEET_NAME);
var rows = settingsSheet.getDataRange();
var numRows = rows.getNumRows();
var numCols = rows.getNumColumns();
var values = rows.getValues();
var numSettingsRows = numRows - 1;
var sortString = "";
var filters = new Array();
for(var i = 0; i < numRows; i++) {
var row = values[i];
var settingName = row[0];
var settingOperator = row[1];
var settingValue = row[2];
var dataType = row[3];
debug(settingName + " " + settingOperator + " " + settingValue);
if(settingName.toLowerCase().indexOf("report type") != -1) {
var reportType = settingValue;
} else if(settingName.toLowerCase().indexOf("date range") != -1) {
var dateRange = settingValue;
} else if(settingName.toLowerCase().indexOf("sort order") != -1) {
var sortDirection = dataType || "DESC";
if(settingValue) var sortString = "ORDER BY " + settingValue + " " + sortDirection;
var sortColumnIndex = 1;
}else {
if(settingOperator && settingValue) {
if(dataType.toLowerCase().indexOf("long") != -1 || dataType.toLowerCase().indexOf("double") != -1 || dataType.toLowerCase().indexOf("money") != -1 || dataType.toLowerCase().indexOf("integer") != -1) {
var filter = settingName + " " + settingOperator + " " + settingValue;
} else {
if(settingValue.indexOf("'") != -1) {
var filter = settingName + " " + settingOperator + ' "' + settingValue + '"';
} else if(settingValue.indexOf("'") != -1) {
var filter = settingName + " " + settingOperator + " '" + settingValue + "'";
} else {
var filter = settingName + " " + settingOperator + " '" + settingValue + "'";
}
}
debug("filter: " + filter)
filters.push(filter);
}
}
}
// Process the report sheet and fill in the data
var reportSheet = SpreadsheetApp.openByUrl(currentSetting.ss).getSheetByName(REPORT_SHEET_NAME);
var rows = reportSheet.getDataRange();
var numRows = rows.getNumRows();
var numCols = rows.getNumColumns();
var values = rows.getValues();
var numSettingsRows = numRows - 1;
// Read Header Row and match names to settings
var headerNames = new Array();
var row = values[0];
for(var i = 0; i < numCols; i++) {
var value = row[i];
headerNames.push(value);
//debug(value);
}
if(reportType.toLowerCase().indexOf("performance") != -1) {
var dateString = ' DURING ' + dateRange;
} else {
var dateString = "";
}
if(filters.length) {
var query = 'SELECT ' + headerNames.join(",") + ' FROM ' + reportType + ' WHERE ' + filters.join(" AND ") + dateString + " " + sortString;
} else {
var query = 'SELECT ' + headerNames.join(",") + ' FROM ' + reportType + dateString + " " + sortString;
}
debug(query);
var report = AdWordsApp.report(query);
try {
report.exportToSheet(reportSheet);
var subject = "Your " + reportType + " for " + dateRange + " for " + AdWordsApp.currentAccount().getName() + " is ready";
var body = currentSetting.ss + "<br>You can now add this data to <a href='https://www.optmyzr.com'>Optmyzr</a> or another reporting system.";
MailApp.sendEmail(EMAIL_ADDRESSES, subject, body);
Logger.log("Your report is ready at " + currentSetting.ss);
Logger.log("You can include this in your scheduled Optmyzr reports or another reporting tool.");
} catch (e) {
debug("error: " + e);
}
}
function debug(text) {
if(DEBUG) Logger.log(text);
}
I've tried overwriting the data validation in the host spreadsheet, but think I need to amend the script itself also.

How can I make this XMLHttpRequest for Leaflet more simple? Just vanilla JS

Can this be better? More simple?
My Steps:
Created a Google Doc Sheet -spread sheet
Exported as json
Build this ajax js script to make available to leaflet. js app.
https://jsfiddle.net/lukedohner/by80bvL7/
There maybe a more succinct way.
xhr.onload = function() {
console.log("onload + function");
if (xhr.status === 200) {
//sucessfull load of json
alert("Here is the data in a alert window " + xhr.responseText);
var respText = xhr.responseText;
xhrText = JSON.parse(respText); // convert it to an object
console.log(
"json data: xhrText.length >>>>>>>> " +
Object.keys(xhrText.mysheet).length
);
console.log(
"Object.keys(xhrText) >>>>>>>> " + Object.keys(xhrText)
);
var i = -1;
for (var mykey in xhrText.mysheet) {
//In case you want to check to see it there is a null value -property
if (xhrText.mysheet.hasOwnProperty(mykey)) {
i++;
window["card" + i] = mykey + " -> " + xhrText[mykey];
}
}
} else {
// not sucessfull load of json
alert("Request failed. Returned status of " + xhr.status);
}
createhooks();
};
};
var ch = {}; // create a var namespace
createhooks = function() {
var mysheetlenght = Object.keys(xhrText.mysheet).length;
for (var j = 0; j < mysheetlenght; j++) {
//console.log(" xhrText.title >>>>>>>> " + j + " " + xhrText.mysheet[j].title);
ch["title" + j] = xhrText.mysheet[j].title;
ch["subtitle" + j] = xhrText.mysheet[j].subtitle;
ch["copy" + j] = xhrText.mysheet[j].copy;
ch["imagename" + j] = xhrText.mysheet[j].imagename;
console.log("title" + j + " is " + ch["title" + j]);
console.log("subtitle" + j + " is " + ch["subtitle" + j]);
console.log("copy" + j + " is " + ch["copy" + j]);
console.log("imagename" + j + " is " + ch["imagename" + j]);
console.log("~~~~~ " + "~~~~~ ");
//create vars for addLElement function - Display it is the DOM
titleindex = "ch.title" + j;
addElement("Title " + j, ch["title" + j]);
subtitleindex = ["ch.subtitle" + j];
addElement("Subtitle " + j, ch["subtitle" + j]);
copyindex = ["ch.copy" + j];
addElement("Copy " + j, ch["copy" + j]);
imagenameindex = ["ch.imagename" + j];
addElement("Image Name " + j, ch["imagename" + j]);
addElement("~~~~~ ", "~~~~~");
}
ch_callback();
};
function ch_callback() { // Use ch.title1, ch.title1, ch.title1, ch.title1, ch.title1... in your add addElement function or in the Leaflet.js L.control.window method
console.log("callback " + ch.copy1);
}
Now I can use the var like this ch.copy1 in the leaflet L.control.window method. Not shown in fiddle example.

Code studio javascript

So I'm basically making an savings account system. A user can set up an account and start with a balance of 0 the withdraw and deposit money whenever they want. It works perfectly the first few times but then it gives me the RangeError either when I try logging in or out.
setScreen('LogIn');
var balance;
var curbal = [];
var totalAccts=[];
onEvent("saveAcct", "click", function() {
var username = getText('createUserInput');
var password = getText('createPassInput');
appendItem(totalAccts, getText('createUserInput') + " " +
getText('createPassInput') + " ");
console.log("Username: " + username + " Password: " + password);
console.log(totalAccts);
setScreen('LogIn');
});
onEvent('makeAcct', 'click', function(){
setScreen('CreateAcct');
setText('createUserInput', "");
setText('createPassInput', "");
setText("userInput", "");
setText("passInput", "");
hideElement('alert');
});
onEvent('addMoney', 'click', function(){
setNumber('balance', balance + getNumber('addInput'));
balance = balance + getNumber('addInput');
setNumber('addInput', '');
console.log(balance);
});
onEvent('subMoney', 'click', function(){
setNumber('balance', balance - getNumber('subInput'));
balance = balance - getNumber('subInput');
setNumber('subInput', '');
console.log(balance);
});
onEvent('login', 'click', function(){
balance = 0;
changeEnBal(totalAccts, curbal);
});
onEvent('logout', 'click', function(){
changeExBal(totalAccts, getNumber('balance'), curbal);
hideElement('alert');
setText('balance', 0);
setText("userInput", "");
setText("passInput", "");
setScreen('LogIn');
});
onEvent("goBack", "click", function() {
setScreen('LogIn');
});
function changeEnBal(list, balList) {
var user = getText('userInput');
var pass = getText('passInput');
for (var i = 0; i < list.length; i++) {
if (list[i] === (user + " " + pass + " ")) {
setScreen('Account');
} else {
for (var a = 0; a < balList.length; a++) {
if (list[i] === (user + " " + pass + " " + balList[a])) {
balance = balList[a];
setNumber('balance', balList[a]);
setScreen('Account');
console.log(balList[a]);
}
}
}
}
for (var b = 0; b < balList.length; b++) {
if (balList[b] != (user + " " + pass + " " + balList[b])){
showElement('alert');
}
}
}
function changeExBal(list, curBal, balList) {
var user = getText('userInput');
var pass = getText('passInput');
for (var i = 0; i < list.length; i++) {
if (list[i] === (user + " " + pass + " ")) {
list[i] = user + " " + pass + " " + curBal;
appendItem(curbal, curBal);
console.log(curbal);
console.log(list[i]);
} else {
for (var a = 0; a < balList.length; a++) {
if (list[i] === (user + " " + pass + " " + balList[a])) {
balList[a] = curbal;
list[i] = user + " " + pass + " " + curBal;
}
}
}
}
console.log(totalAccts);
}
As suggested in some of the comments I would change your for loops to start with a zero index:
for (var i = 0; i < list.length; i++)
and
for (var a = 0; a < balList.length; a++)

Google Api Calendar If else ,done with javascript

So I'm doing Google Calendar Api, that shows all the booked things for that day. I'm trying to get this code to print 'Vapaa' (means free in finnish and is shown if there's nothing booked in that time) only once but still print the rest of the appointments that come later that day. Here's the code that does the if else
if (events.length > 0) {
for (i = 0; i < events.length; i++) {
var event = events[i];
var when = new Date(event.start.dateTime);
var hs = addZero(when.getHours());
var ms = addZero (when.getMinutes());
var end = new Date(event.end.dateTime);
var he = addZero(end.getHours());
var me = addZero (end.getMinutes());
var now = new Date();
var hn = addZero(now.getHours());
var mn = addZero (end.getMinutes());
if (!when) {
when = event.start.date;
}
if (when.getTime() <= now.getTime() && now.getTime() <= end.getTime()){
appendPre(event.summary + ' ' + hs + (':') + ms + '' + (' - ') + '' + he + (':') + me + '');
} else {
appendPre('Vapaa');
appendPre(event.summary + ' ' + hs + (':') + ms + '' + (' - ') + '' + he + (':') + me + '');
}
return;
}
} else {
appendPre('Ei varauksia');
}
Also the appendPre is printed to html with this code
function appendPre(message) {
if (message != 'Vapaa'){
var pre = document.getElementById('booked');
var textContent = document.createTextNode(message + '\n' + '\n');
} else {
var pre = document.getElementById('free');
var textContent = document.createTextNode(message + '\n' + '\n');
}
pre.appendChild(textContent);
}
I'm so lost so any help would be awesome.
return; stops right where it is and exits the function, so your for loop will only run once with the return in there. See W3C for more info.
Typically, if you want to exit only the loop, but continue in the function (if you have code after it, it doesn't look like you've shown that here), you can use break;. If you want to skip the rest of the stuff in the for loop (nothing is shown in your example), but continue iterating onto the next entry, you can use continue;. See W3C for more details.

How to fix this js code?

I didn't write this code, but I'm still a beginner, can anyone help me with the bugs in this? JSLint kept giving me several bugs and I couldn't seem to fix them. It would be every much appreciated. I'm learning as I post this. I'm currently working on improving my graphic/motion design skills and coding skills. But I can't write something like this currently. If there is anymore detail you need, you can just comment and ask. Thanks.
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://209.15.211.170/catalog/", false);
xhr.send();
console.log(xhr.status);
console.log(xhr.statusText);
$("html").html("<h2 style='position:absolute;left:60%;color:#BF34334;font-family:arial;'></h2>");
var minPage = 1;
var maxPage = 12;
var page = minPage;
var json = 'http://209.15.25843811.170/catalog/json?browse&Category=2';
var min = 1;
var max = Number(prompt("Maximum Robux?"));
function buy(item, price) {
"use strict";
var link = 'http://209.15.211.170/';
$.get(link, function(data) {
var info = (data).find('.ItemSalesTable'.find('.PurchaseButton')).data();
var buy = 'http://www.roblox.com/API/Item.aspx?rqtype=purchase&productID=' + info[productId] + '&expectedcurrency=1&expectedPrice=' + info[expectedPrice] + '&expectedSellerId=' + info[expectedSellerId] + & userAssetID = +info[userassetId];
if (parseInt(info) == parseInt(info['expectedPrice'])) {}
});
}
setInterval(function(3000) {
function get() {
$.get(json, function(Data) {
for (var Hat & Data {
if (max >= Price && Price > 0) {
buy(ID, Price)
var dt = new Date();
var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds();
console.info(Name + '[' + Price + '] # ' + time);
}
}
})
}
get()
console.clear();
console.info('Running on pages ' + minPage + '-' + maxPage);
confirm = function() {};
alert = function() {};
console.clear();
Not entirely sure what your needs are, but try replacing your code with this:
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://209.15.211.170/catalog/", false);
xhr.send();
console.log(xhr.status);
console.log(xhr.statusText);
$("html").html("<h2 style='position:absolute;left:60%;color:#BF34334;font-family:arial;'></h2>");
var minPage = 1;
var maxPage = 12;
var page = minPage;
var json = 'http://209.15.25843811.170/catalog/json?browse&Category=2';
var min = 1;
var max = Number(prompt("Maximum Robux?"));
function buy(item, price) {
"use strict";
var link = 'http://209.15.211.170/';
$.get(link, function(data) {
var info = (data).find('.ItemSalesTable'.find('.PurchaseButton')).data();
var buy = 'http://www.roblox.com/API/Item.aspx?rqtype=purchase&productID=' + info[productId] + '&expectedcurrency=1&expectedPrice=' + info[expectedPrice] + '&expectedSellerId=' + info[expectedSellerId] + '&userAssetID=' +info[userassetId];
if (parseInt(info) == parseInt(info['expectedPrice'])) {}
});
};
function get() {
$.get(json, function(Data) {
for (var Hat in Data) {
if (max >= Price && Price > 0) {
buy(ID, Price);
var dt = new Date();
var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds();
console.info(Name + '[' + Price + '] # ' + time);
}
}
});
};
setInterval(function() {
get();
console.clear();
console.info('Running on pages ' + minPage + '-' + maxPage);
confirm = function() {};
alert = function() {};
console.clear();
}, 3000);

Categories