Google maps API checking is element exists - google-maps-api-3

I'm calling google maps geocode and looping over the address_components struct and tring to output the city name. I'd like to store the postal_town as the city name but if it does not exist then use the administrative_area_level_2 instead.
The problem is that even if a postal_town is returned the administrative_area_level_2 is still being used. Can anybody see what i'm doing wrong?
for(var i=0, len=result.address_components.length; i<len; i++) {
var ac = result.address_components[i];
if(ac.types.indexOf("postal_town") >= 0){
state = $('#sharesparestepAddressCity').val(ac.long_name);
}else if(ac.types.indexOf("administrative_area_level_2") >= 0){
state = $('#sharesparestepAddressCity').val(ac.long_name);
}
}

If both exist, your code will return the last one found. Add a break to stop processing when you find the one you want.
for(var i=0, len=result.address_components.length; i<len; i++) {
var ac = result.address_components[i];
if(ac.types.indexOf("postal_town") >= 0){
state = $('#sharesparestepAddressCity').val(ac.long_name);
break;
} else if(ac.types.indexOf("administrative_area_level_2") >= 0){
state = $('#sharesparestepAddressCity').val(ac.long_name);
}
}

Related

Dictionary Syntax Error in Google Apps Script

I have a function that creates a dictionary based on a series of values from a sheet. I then try to pull one of the values from that sheet using a key. It works fine to log to the console. However, in an if statement, it says syntax error and nothing else. I cannot figure it out. Here is the function and the code that crashes. This problem only occurs in the for loop, and does not occur outside of it.
//creates dictionary
function columnLocationWithNotation(notation) {
var spreadsheet = SpreadsheetApp.openByUrl();
var sheet = spreadsheet.getActiveSheet();
var data = sheet.getDataRange();
var cells = data.getValues();
var dictionary = {};
switch (notation) {
case "zeroIndex":
for (var i = 0; i < sheet.getLastRow(); i++) {
dictionary[cells[i][0]] = cells[i][1]
}
return dictionary
break;
case "regularIndex":
for (var i = 0; i < sheet.getLastRow(); i++) {
dictionary[cells[i][0]] = cells[i][2]
}
return dictionary
break;
case "string":
for (var i = 0; i < sheet.getLastRow(); i++) {
dictionary[cells[i][0]] = cells[i][3]
}
return dictionary
break;
}
}
var master0indexDictionary = columnLocationWithNotation("zeroIndex")
for (var i = 1; i =< (sheet.getLastRow() - 1); i++) {
var phone = master0indexDictionary["Tutor Name"]
if (cells[i][phone] === phoneNumber) { //LINE WITH SYNTAX ERROR
//do something
}
It's not the highlighted line that is causing the problem, even though there are many other issues with your script. There's no '=<' operator in JavaScript. Use '<=' instead:
for (var i = 1; i <= (sheet.getLastRow() - 1); i++) {
Also, as Tanaike pointed out, your 'cells' variable is only defined in the context of your 'columnLocationWithNotation(notation)' function and will not be accessible from the global context. Globally-defined variables are visible from the functions you declare inside the global object, but not vice versa. Same applies to the 'sheet' variable. The 'phoneNumber' variable doesn't seem to be defined, at least not in the snippet of code you provided.
Note that putting 'break' after 'return' statements is redundant.
return dictionary;
break;
You can just return out of 'switch' statement without using breaks, or leave the breaks and put a single 'return' statement after 'switch'.
Finally, always put a semicolon at the end of the line. Doing so will help you avoid many potential pitfalls and issues with JS parser. I noticed several instances where you omitted the semicolon:
return dictionary
break;
var phone = master0indexDictionary["Tutor Name"]
For example, the following code will break if you don't have a habit of putting the semicolon in its rightful place
var a = {name: 'John'} //no semicolon
[a].forEach(function(element) {
Logger.log(element); //logs undefined
})
The JS parser treats this code as one line, so 'a' will still be 'undefined' by the time you call the 'forEach()' loop on the array.

How to compare values between a 2 dimensional and one dimesional array?

Array1:
[[P01, 153425], [P02, 3951990], [P03, 106658], [P04, 4563594], [P05, 60198], [P07, 326292], [P08, 1265], [P09, 108293], [P10, 183698], [P11, 5084]] this comes from BigQuery.
Array2:
[[P01], [P02], [P03], [P04], [P05], [P06], [P07], [P08], [P09], [P10], [P11]]
this array is fetched from google sheet column using sheet.getSheetValues(3,1,11,1);
Based on this i should update a column in google sheet based on the matching values between Array1 and Array2:
eg: [153425,3951990,106658,4563594,60198,326292,1265,108293,183698,5084]
if value does not match the corresponding value should remain empty.
Compare Array1[i][0] with Array2[j] inside for loop, if it is equal take the value of Array1[i][1]
for(var i=0; i<Array1.length; i++){
for(var j=0; j<Array2.length; j++){
if(Array1[i][0] == Array2[j]){
//do something
//if it can be equal to only one number, you can break it here
}
}
}
EDIT
Then you should compare Array2[i] with Array1[j][0]
for(var i=0; i<Array2.length; i++){
var isExist = false;
for(var j=0; j<Array1.length; j++){
if(Array2[i] == Array1[j][0]){
//do something
//if it can be equal to only one number, you can break it here
isExist = true;
}
}
if(!isExist){
//do something if it does not exist
}
}

How to create an object from 2 arrays?

So I hava array Links and array Params with same langth N
So what I need is to create an object where for each link from Links I will be able to see
param from Params
And than for example to be abble to call something like
for each( item in object)
if (item.param == "some value") {
// some code
} else...
How to do such thing (Code exaMple, please)
From Array: You could first build a list with elements composed of a item and a param (supposing the length is indeed the same for both lists)
var items:Array = new Array();
for(var i:uint = 0; i < links.length; i++) {
links:Array .push({link:links[i], param:params[i]});
}
You can then filter them easily:
items.forEach(checkValue);
for(var i:uint = 0; i < items.length; i++) {
if (items[i].param == "some value") {
// some code
} else{
...
}
}

ASP.Net Webforms w/ AJAX Slow Rendering

I have a Webforms, AJAX-enabled web page which, when rendering large amounts of data, is extremely slow to load in IE (we're married to IE - no other browser options). In an attempt to determine the source of the slowness, I viewed the HTML source (about 2.5 MB) and copied all of it (except for the Ajax JavaScript calls) to a blank .html file. IE renders this file MUCH faster than when the rendering happens through .Net. This seems to indicate that the AJAX JavaScript is slowing down the display of the page. Does this sound plausible? Any recommendations on improving performance here?
I've already eliminated as many UpdatePanel controls as I can from the page, but it doesn't seem to help with render time.
Thanks for the help!
Update... In the HTML source, I noticed that at the bottom of the screen, a call to WebForm_InitCallback() appears. When I executed this call directly through javascript:alert(WebForm_InitCallback());, the CPU spikes for 12 seconds before it completes! This call is here because I implemented ICallbackEventHandler to try to accomplish some traditional-style AJAX handling. Looking at WebResource.axd, that WebForm_InitCallback() method iterates through the entire form and attaches some kind of events to EVERY SINGLE textbox, checkbox, radiobutton, etc. So I guess I really need to abandon ScriptManager and UpdatePanel altogether here. Poop.
Andy
I hate to say this, but can you take the Microsoft AJAX out of the equation? Try it with doing an XMLHTTP request and populate the data yourself. That way at least you could step through the js and figure out if it is time on the server, time turning the resulting XML or JSON into an object, or time spent populating your data on screen.
This is an old topic but I thought I should share what I recently did to fix long running script error in IE 7 caused by WebForm_InitCallback.
I had a page with over 2000 form elements and in IE 7 was causing a long running script warning / browser freeze for a client. We have other pages with many more form elements and paging or other options aren't options due to needing a quick turn around to improve performance.
I narrowed it down to WebForm_InitCallback, and even further to the following line:
element = theForm.elements[i];
By saving a reference to theForm.elements instead and using it to access the index, I found significant performance gains.
var elements = theForm.elements;
for (var i = 0; i < count; i++) {
element = elements[i];
....
}
I made a jsperf to test the difference since I didn't expect such impressive gains from not calling the refinement every time.
Beyond that, I found better performance by replacing the concatenation in WebForm_InitCallbackAddField to adding the strings to an array and joining it together after the for loop in WebForm_InitCallback completes and saving it back into __theFormPostData.
Here are the original two function that you'll see in the WebResource:
function WebForm_InitCallback() {
var count = theForm.elements.length;
var element;
for (var i = 0; i < count; i++) {
element = theForm.elements[i];
var tagName = element.tagName.toLowerCase();
if (tagName == "input") {
var type = element.type;
if ((__callbackTextTypes.test(type) || ((type == "checkbox" || type == "radio") && element.checked))
&& (element.id != "__EVENTVALIDATION")) {
WebForm_InitCallbackAddField(element.name, element.value);
}
}
else if (tagName == "select") {
var selectCount = element.options.length;
for (var j = 0; j < selectCount; j++) {
var selectChild = element.options[j];
if (selectChild.selected == true) {
WebForm_InitCallbackAddField(element.name, element.value);
}
}
}
else if (tagName == "textarea") {
WebForm_InitCallbackAddField(element.name, element.value);
}
}
}
function WebForm_InitCallbackAddField(name, value) {
var nameValue = new Object();
nameValue.name = name;
nameValue.value = value;
__theFormPostCollection[__theFormPostCollection.length] = nameValue;
__theFormPostData += WebForm_EncodeCallback(name) + "=" + WebForm_EncodeCallback(value) + "&";
}
And here is the javascript I added to my page to overwrite them. It's important that this code is inserted after the WebResource is added and before WebForm_InitCallback is called.
var __theFormPostDataArr = [];
if (typeof (WebForm_InitCallback) != "undefined") {
WebForm_InitCallback = function () {
var count = theForm.elements.length;
var element;
var elements = theForm.elements;
for (var i = 0; i < count; i++) {
element = elements[i];
var tagName = element.tagName.toLowerCase();
if (tagName == "input") {
var type = element.type;
if ((type == "text" || type == "hidden" || type == "password" ||
((type == "checkbox" || type == "radio") && element.checked)) &&
(element.id != "__EVENTVALIDATION")) {
WebForm_InitCallbackAddField(element.name, element.value);
}
}
else if (tagName == "select") {
var selectCount = element.options.length;
for (var j = 0; j < selectCount; j++) {
var selectChild = element.options[j];
if (selectChild.selected == true) {
WebForm_InitCallbackAddField(element.name, element.value);
}
}
}
else if (tagName == "textarea") {
WebForm_InitCallbackAddField(element.name, element.value);
}
}
__theFormPostData = __theFormPostDataArr.join('');
}
WebForm_InitCallbackAddField = function (name, value) {
__theFormPostDataArr = [];
var nameValue = new Object();
nameValue.name = name;
nameValue.value = value;
__theFormPostCollection[__theFormPostCollection.length] = nameValue;
__theFormPostDataArr[__theFormPostDataArr.length] = WebForm_EncodeCallback(name);
__theFormPostDataArr[__theFormPostDataArr.length] = "=";
__theFormPostDataArr[__theFormPostDataArr.length] = WebForm_EncodeCallback(value);
__theFormPostDataArr[__theFormPostDataArr.length] = "&";
}
}
Ultimately, it took the run time of WebForm_InitCallback from 27 seconds to 4 seconds on my IE 7 machine.

JsonArray in silverlight to javascript

I'm creating a JsonArray such as:
JsonArray jsonValues = new JsonArray();
for( int i = 0; i < values.Count; i++ )
{
var someSingleValue = values[i];
jsonValues.Add( string.Format( "Name: {0}", someSingleValue ) );
}
After that I'm shipping json values to my javascript in .aspx page via call:
HtmlPage.Window.Invoke("call", jsonValues);
The call works and it gets there, however I have no idea how to iterate over those values, i.e extract them.
I've tried: (in javascript)
for (var x in somevalues){ alert(somevalues); }
I also tried:
for(var i = 0; i < somevalues.length; i++) {
alert(somevalues[i]);
}
but it crashes.(in both cases)
any ideas?
Are you using the eval method to serialize the string to a JSON object?
function call(somevalues){
//somevalues is currently just a string.
var results = eval("(" + somevalues +")");
//results now should contain your array as a JSON object.
//and you should be able to iterate over it at this point.
for(var i = 0; i < results.length; i++){
alert(results[i]);
}
}
Assuming somevalues is truly an array, you do it like this:
for(var i = 0; i < somevalues.length; i++) {
// do something with somevalues[i]
}
What you did was tell JavaScript to iterate over the properties of the somevalues object, which is similar, but not the same, as the iteration using a regular for loop.
EDIT: I am willing to bet your variable, somevalues is a string. Just do alert(somevalues) and see what happens.

Resources