Fusion Table Query via Google Visualization - google-visualization

function createBoundingBox() {
outputDiv = document.getElementById('outputDiv');
outputDiv.innerHTML = '';
var queryList = [];
queryList.push("SELECT 'WEB', 'NAME', 'ADDRESS', 'Lat', 'Lng', 'WEB1' FROM ");
queryList.push(Table);
queryList.push(" WHERE " + where + " AND ");
queryList.push("ST_INTERSECTS('GEOMETRY', ");
queryList.push("RECTANGLE(LATLNG");
queryList.push(sw);
queryList.push(", LATLNG");
queryList.push(ne);
queryList.push("))");
var query = encodeURIComponent(queryList.join(''));
var gvizQuery = new google.visualization.Query(
'http://www.google.com/fusiontables/gvizdata?tq=' + query);
gvizQuery.send(function(response) {
numRow = response.getDataTable().getNumberOfRows();
var datatable = response.getDataTable();
if (datatable && datatable.getNumberOfRows()) {
// var linkList = [];
var newLinkList = [];
for (var i = 0; i < numRow; i++) {
var name = response.getDataTable().getValue(i, 1);
nameList.push(name);
var address = response.getDataTable().getValue(i, 2);
addressList.push(address);
var latitude = new google.maps.LatLng(response.getDataTable().getValue(i, 3)); alert(latitude)
latitudeList.push(latitude);
var longitude = new google.maps.LatLng(response.getDataTable().getValue(i, 4));
longitudeList.push(longitude);
var newLink = response.getDataTable().getValue(i, 5);
newLinkList.push("<a name = 'link' id="+"'" + i + "'" + "onmouseover='getId(this)' href=" + newLink + " target='_blank'>" + name + "</a>");
infoContent.push("name" + name + "<br>address: "+address);
// var link = response.getDataTable().getValue(i, 0);
// linkList.push(link);
}
names = newLinkList.join("<br>") ;
outputDiv.innerHTML = numRow+ " results nearby " + sAddress + "<br><br>";
outputDiv.innerHTML += names;
}
});
}
This is the code that is querying the data from the Fusion Table. I'm wondering why the Latitude and Longitude are showing up as (30.xxx, NaN) and (-97.xxx, NaN) when it should be just 30.xxx and -97.xxx. Thank you for your help!

At a guess, column 3 in your data is latitude and column 4 is longitude, correct? If so, then your problem is that you are using google.maps.LatLng incorrectly. The LatLng constructor expects a (lat, long) pair as the arguments, ie:
var latLng = new google.maps.LatLng(latitude, longitude);
and it returns a LatLng object. So, when you call it like this:
var latitude = new google.maps.LatLng(response.getDataTable().getValue(i, 3));
var longitude = new google.maps.LatLng(response.getDataTable().getValue(i, 4));
the constructor thinks you are giving it a latitude with no longitude each time. What you want to do is this:
var inputLatitude = response.getDataTable().getValue(i, 3);
var inputLongitude = response.getDataTable().getValue(i, 3);
var latLng = new google.maps.LatLng(inputLatitude, inputLongitude);
latitudeList.push(latLng.lat());
longitudeList.push(latLng.lng());

This:
var latitude = new google.maps.LatLng(response.getDataTable().getValue(1, 3));
latitudeList.push(latitude);
var longitude = new google.maps.LatLng(response.getDataTable().getValue(i, 4));
longitudeList.push(longitude);
Probably should be:
var latitude =response.getDataTable().getValue(i, 3);
latitudeList.push(latitude);
var longitude = response.getDataTable().getValue(i, 4);
longitudeList.push(longitude);
Or put the combined google.maps.LatLng onto a single array
var latitude =response.getDataTable().getValue(i, 3);
var longitude = response.getDataTable().getValue(i, 4);
latlngList.push(new google.maps.LatLng(latitude,longitude));

Related

Regex in textreplace google app script is not working

Trying to replace text + date just by date using regex, but it not works:
function myfunction() {
var SourceFolder = DriveApp.getFolderById("");
var Files = SourceFolder.getFiles()
var body = DocumentApp.getActiveDocument().getBody();
while(Files.hasNext()) {
var file = Files.next();
body.replaceText("Date: \d{2}.\d{2}.\d{4}", "31.10.2020")
}
}
Thanks
In your code, var body = DocumentApp.getActiveDocument().getBody(); is declared outside of the loop, so you always refer to the active document body in your while loop.
You may use
while(Files.hasNext()) {
var file = Files.next();
var doc = DocumentApp.openById(file.getId());
var body = doc.getBody();
body.replaceText("Date: \\d{2}\\.\\d{2}\\.\\d{4}", "31.10.2020")
}
The point here is to use double backslashes in the pattern, and escape the dot chars since otherwise a . matches any char but a line break char.
function replace_text() {
// Get speadshhet with ID
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
// Returns cell with ID (User will insert his or her folder ID in cell B3)
var range = sheet.getRange(3, 2);
var values = range.getDisplayValue();
// Get folder by ID - insert your folder ID
var SourceFolder = DriveApp.getFolderById(values);
// Iterate throw all files in folder
var Files = SourceFolder.getFiles();
while(Files.hasNext()) {
var file = Files.next();
// Get all documents ID
var doc = DocumentApp.openById(file.getId());
// Get text body to replace
var body = doc.getBody();
// Insert header in document + alignment
var header = body.insertParagraph(0, 'TEXT');
header.setAlignment(DocumentApp.HorizontalAlignment.RIGHT)
// Text style
var style = {};
//style[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.RIGHT;
style[DocumentApp.Attribute.FONT_FAMILY] = 'Arial';
style[DocumentApp.Attribute.FONT_SIZE] = 9;
style[DocumentApp.Attribute.FOREGROUND_COLOR] = '#000000';
body.setAttributes(style)
Logger.log(body)
// Replacing text
body.replaceText("Text", " ");
body.replaceText("Date:\\s*\\d{2}\\.\\d{2}\\.\\d{4}", "31.10.2020")
var paragraphs = body.getParagraphs();
for (var i = 7; i < paragraphs.length; i++) {
var paragraph = paragraphs[i];
paragraph.setAlignment(DocumentApp.Horizontal`enter code here`Alignment.LEFT)
}
}
}

Array & slideshow

I'm using the below code in order to display a photo in slide show, i need to display: name,job and quote for each person, but actually only photos change on time interval specified ...can anyone help?
var img1 = document.getElementById("img1");
var testname = document.getElementById("testname");
var testjob = document.getElementById("testjob");
var testpa = document.getElementById("testpa");
var currentPos = 0;
var images = ["ch1.jpg", "ch2.jpg", "ch3.jpg"]
var testname = [“John Smith” ,”Jan Rosso”,”Raphael Matthew”]
var testjob = [“Manager” ,”Director”,”Supervisor”]
var testpa = [“I like this company”,”It’s amazing”,”Wondeful atmospher”]
function volgendefoto() {
if (++currentPos >= images.length)
currentPos = 0;
img1.src = images[currentPos];
testname.value = testname[currentPos];
testjob.value = testjob[currentPos];
testpa.value = testpa[currentPos];
}
setInterval(volgendefoto, 3000);
function test(){
document.getElementById('text').value=document.getElementById('testname').value
}
testName and the others may need to be updated via innerHTML
function volgendefoto() {
if (++currentPos >= images.length)
currentPos = 0;
img1.src = images[currentPos];
testname.innerHtml = testname[currentPos];
testjob.innerHtml = testjob[currentPos];
testpa.innerHtml = testpa[currentPos];
}

Problem with If/Then code with Google Sheet Script

Someone please help.
I am trying to create a simple script which records button presses in order.
I have:
function P1Buzzer() {
var sheet = SpreadsheetApp.getActiveSheet();
var row = 6;
var col = 1;
var Name = sheet.getRange(row, col).getValue();
var sheet = SpreadsheetApp.getActiveSheet();
var row = 192;
var col = 1;
var AnswerPosition = sheet.getRange(row, col).getValue();
if (AnswerPosition = 1) {
sheet.getRange(199, 1).setValue(Name);
var AnswerPosition = AnswerPosition + 1
sheet.getRange(192, 1).setValue(AnswerPosition);
}
if (AnswerPosition = 2) {
sheet.getRange(200, 1).setValue(Name);
var AnswerPosition = AnswerPosition + 1
sheet.getRange(192, 1).setValue(AnswerPosition);
}
}
The problem I have is that when I run the script it does both the commands, ignoring the if command.
Any ideas?
First, you are setting the value to 1 by using = instead of ==. Second, if it was 1, you add one to it and then check to see if it is 2. I'll bet it is!
if (AnswerPosition == 1) {
sheet.getRange(199, 1).setValue(Name);
var AnswerPosition = AnswerPosition + 1
sheet.getRange(192, 1).setValue(AnswerPosition);
} else if (AnswerPosition == 2) {
...

Google Apps Scripts If function not skipping rows with null value

I am writing a function that will search a spreadsheet for days an employee has worked hours, create an array with the values for job number, job name, employee name, hours, and date, and then put them onto another spreadsheet. It also only shows hours that were within the past 8 days so that time can be worked out for the week when we have to report hours (I'm scheduling it to run the day time is due). I also have been filtering out days with blank hours, which limits the amount of data that gets copied over.
I am encountering an issue where on one employee the function to skip the blank hours does not work. For other employees I have been able to use "" to indicate an empty cell. I have also tried to use (null) as a value, but that only ignores 6 of 7 days (It still logs days with no hours that are adjacent to cells that calculate hours in the week).
What I can't figure out is why this doesn't work on just one sheet out of the whole Google Sheets document. I have simplified my spreadsheet to reduce personal information, and to make it easier to parse the script, but in my original document I track 6 employees with similar code, and only one is showing this issue.
https://docs.google.com/spreadsheets/d/1ve0EPVQJ2vmWG1NYHMncw1ZljP3yXd28dMeNC38Jiy4/edit?usp=sharing
Is a link to the spreadsheet. Code is below.
function shoptime(){
var ss = SpreadsheetApp.getActive().getId();
var stephensheet = Sheets.Spreadsheets.Values.get(ss, 'Stephen!A2:G');
var tiffanysheet = Sheets.Spreadsheets.Values.get(ss, 'Tiffany!A2:G');
var scripts = SpreadsheetApp.getActive().getSheetByName("Scripts");
var currentDate = new Date();
var pastweek = new Date();
pastweek.setDate(currentDate.getDate() -8);
var array=[];
for (var a = 0; a < stephensheet.values.length; a++){
var jobdate = stephensheet.values[a][1];
var intime = stephensheet.values[a][2];
var outtime = stephensheet.values[a][3];
var dailyhours = stephensheet.values[a][4];
if (new Date(jobdate) > pastweek){
if (dailyhours != (null)){
array.push(["NA","Office","Stephen",dailyhours,jobdate]);
}
}
}
for (var a = 0; a < tiffanysheet.values.length; a++){
var jobdate = tiffanysheet.values[a][1];
var intime = tiffanysheet.values[a][2];
var outtime = tiffanysheet.values[a][3];
var dailyhours = tiffanysheet.values[a][4];
if (new Date(jobdate) > pastweek){
if (dailyhours != ("")){
array.push(["NA","Office","Tiffany",dailyhours,jobdate]);
}
}
}
if(array[0]){
scripts.getRange(scripts.getLastRow()+1,1,array.length,5).setValues(array);
}
SpreadsheetApp.flush();
}
I'm not sure of the exact issue but checking for cells that have a value rather than cells that are not null should work for you.
function shoptime(){
var ss = SpreadsheetApp.getActive().getId();
var stephensheet = Sheets.Spreadsheets.Values.get(ss, 'Stephen!A2:G');
var tiffanysheet = Sheets.Spreadsheets.Values.get(ss, 'Tiffany!A2:G');
var scripts = SpreadsheetApp.getActive().getSheetByName("Scripts");
var currentDate = new Date();
var pastweek = new Date();
pastweek.setDate(currentDate.getDate() -8);
var array=[];
for (var a = 0; a < stephensheet.values.length; a++){
var jobdate = stephensheet.values[a][1];
var intime = stephensheet.values[a][2];
var outtime = stephensheet.values[a][3];
var dailyhours = stephensheet.values[a][4];
if (new Date(jobdate) > pastweek){
if (dailyhours){
array.push(["NA","Office","Stephen",dailyhours,jobdate]);
}
}
}
for (var a = 0; a < tiffanysheet.values.length; a++){
var jobdate = tiffanysheet.values[a][1];
var intime = tiffanysheet.values[a][2];
var outtime = tiffanysheet.values[a][3];
var dailyhours = tiffanysheet.values[a][4];
if (new Date(jobdate) > pastweek){
if (dailyhours){
array.push(["NA","Office","Tiffany",dailyhours,jobdate]);
}
}
}
if(array[0]){
scripts.getRange(scripts.getLastRow()+1,1,array.length,5).setValues(array);
}
SpreadsheetApp.flush();
}
And to modify the code to use the built-in service with is much more straight forward in this case;
function shoptime(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var stephensheet = ss.getSheetByName('Stephen').getDataRange().getValues();
var tiffanysheet = ss.getSheetByName('Tiffany').getDataRange().getValues();
var scripts = ss.getSheetByName("Scripts");
var currentDate = new Date();
var pastweek = new Date();
pastweek.setDate(currentDate.getDate() -8);
var array=[];
for (var a = 0; a < stephensheet.length; a++){
var jobdate = stephensheet[a][1];
var intime = stephensheet[a][2];
var outtime = stephensheet[a][3];
var dailyhours = stephensheet[a][4];
if (new Date(jobdate) > pastweek){
if (dailyhours != ""){
array.push(["NA","Office","Stephen",dailyhours,jobdate]);
}
}
}
for (var a = 0; a < tiffanysheet.length; a++){
var jobdate = tiffanysheet[a][1];
var intime = tiffanysheet[a][2];
var outtime = tiffanysheet[a][3];
var dailyhours = tiffanysheet[a][4];
if (new Date(jobdate) > pastweek){
if (dailyhours != ""){
array.push(["NA","Office","Tiffany",dailyhours,jobdate]);
}
}
}
if(array[0]){
scripts.getRange(scripts.getLastRow()+1,1,array.length,5).setValues(array);
}
SpreadsheetApp.flush();
}
Finally, if you are scraping data from 6 sheets in the exact same format then a another loop and an array of the sheet names will save on repetition of code
function shoptime() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheets = ['Stephen', 'Tiffany'] // add the aditional sheet names here
var scripts = SpreadsheetApp.getActive().getSheetByName("Scripts");
var currentDate = new Date();
var pastweek = new Date();
pastweek.setDate(currentDate.getDate() - 8);
var array = [];
for (var i = 0; i < sheets.length; i++) {
var sheet = ss.getSheetByName(sheets[i]);
var data = sheet.getDataRange().getValues();
for (var a = 0; a < data.length; a++) {
var jobdate = data[a][1];
var intime = data[a][2];
var outtime = data[a][3];
var dailyhours = data[a][4];
if (new Date(jobdate) > pastweek) {
if (dailyhours) {
array.push(["NA", "Office", sheets[i], dailyhours, jobdate]);
}
}
}
}
if (array[0]) {
scripts.getRange(scripts.getLastRow() + 1, 1, array.length, 5).setValues(array);
}
SpreadsheetApp.flush();
}

sencha touch sort list by Distance

i want to sort a list of Locations by its Distance(displayed in list).
i already have a code that sould work but since i am that new to the whole mvc thing, i am not really sure where to place it to make it work.
Maybe someone can help me:
var geocoder = new google.maps.Geocoder();
var geo = Ext.create('Ext.util.Geolocation',{
autoUpdate: false,
listeners: {
locationupdate:{
scope: this,
fn: function(geo){
var haversindeDistance = function(lat1,lon1,lat2,lon2){
if(typeof(Number.prototype.toRad)=="undefined"){
Number.prototype.toRad = function(){
return this * Math.PI/180;
}
}
var R = 6371; //km
var dLat = (lat2-lat1).toRad();
var dLon = (lon2-lon1).toRad();
var lat1 = lat1.toRad();
var lat2 = lat2.toRad();
var a = Math.sin(dLat/2)*Math.sin(dLat/2)+
Math.sin(dLong/2)*Math.sin(dLon/2)*Math.cos(lat1)*Math.cos(lat2);
var c = 2*Math.atan2(Math.sqrt(a),Math.sqrt(1-a));
var d = R*c;
// KM or MIles
//return d*0.621371192; //MIles
return d;
};
var store = Ext.getStore('locationsstore');
store.suspendEvents(true);
store.each(function(location){
var lat2 = parseFloat(location.get(geocoder.geocode( { 'address': sAddress}, function(results, status) { })))||0;
var lon2 = parseFloat(location.get(geocoder.geocode( { 'address': sAddress}, function(results, status) { })))||0;
//var lat2 = parseFloat(location.get('lat'))||0;//try to put geocode on this ish
//var lon2 = parseFloat(location.get('lon'))||0;
if(lat2 && lon2){
var distance = haversineDistance(geo.getLatitude(),geo.getLongitude(),lat2,lon2);
location.set('distance',distance);
}
}, this);
store.resumeEvents();
store.filter('distance',/\d/);
store.sort('distance');//check if it is not done or can not be done somewhere else
list.setMasked(false);
}
},
locationerror:{
scope: this,
fn:function(geo,bTimeout,bPermissionDenied,bLocationUnavailable,message){
console.log([geo,bTimeout,bPermissionDenied,bLocationUnavailable,message]);
if(bTimeout){
Ext.Msg.alert('Timed out getting your location.');
}else{
Ext.Msg.alert('Error getting location. Please make sure location services are enabled on your Device.');
}
list.setMask(false);
}
}
}
});
geo.updateLocation();
i found the Solution.Just adding a Listener to the Navigation/List View should do it. I had too much in the Controller so i decided to put it directly into the View.