using variables in javascript - javascript

From the google maps API documentation I have got this working:
var flightPlanCoordinates = [
new google.maps.LatLng(37.772323, -122.214897),
new google.maps.LatLng(21.291982, -157.821856),
new google.maps.LatLng(-18.142599, 178.431),
new google.maps.LatLng(-27.46758, 153.027892)
];
what ive tried to do is replicate this piece of code with my own loop so I can use previously stored co-ords, like so:
var output;
$.getJSON('DisplayMap.php', function(data) {
var output = "[ ";
for (var i in data.b) {
output+= "new google.maps.LatLng" + "(" + data.b[i].Ya + ", " + data.b[i].Za + ")," + " ";
}
output+= "]";
document.getElementById("placeholder").innerHTML=output;
alert(output);
});
output+= "]";
Ive checked the output and it looks exactly as I want it to. however, when I substitute it in like this is doesnt work:
var flightPlanCoordinates = output;

In your new code you are building a string instead of an array. You should have something like this instead:
var output = [];
for (var i in data.b) {
output.push(new google.maps.LatLng(data.b[i].Ya, data.b[i].Za));
}
In addition, I am slightly confused by the fact that you create a variable named output both inside and outside of getJSON. Keep in mind that getJSON is asynchronous and you will not be able to use the variable from within getJSON immediately after it is called.

You have to set up a correct javascript Array instead of a string. Like this:
var output = [];
$.getJSON('DisplayMap.php', function(data) {
for (var i in data.b) {
output.push(new google.maps.LatLng(data.b[i].Ya, data.b[i].Za));
}
});

Related

Parse JSON server file into HTML list

I've tried to write a script for parsing a JSON file stored in the server and returning its pairs of key/values into list items containing the relevant attributes in colon-separated format.
I've attempted to do it by using native javascript commands. Although the file is parsed successfully and you can realize that by calling for distinct elements with reference numbers (eg. myObject.pets[1].animal or myObject.pets.length) the loop inside the code that is supposed to capture all items is not working.
Here is the code
<!DOCTYPE html>
<html>
<body>
<ul id="animals"></ul>
<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObject = JSON.parse(this.responseText);
var finalString = "";
for (i in myObject.pets.length) {
var currentItem = "<li>" + myObject.pets[i].animal + ": " + myObject.pets[i].name + "</li>";
var finalString = finalString.concat(currentItem);
}
document.getElementById("animals").innerHTML = finalString;
}
};
xmlhttp.open("GET", "animals.json", true);
xmlhttp.send();
</script>
</body>
</html>
The JSON file
>animals.json
{
"pets":[
{ "animal":"dog", "name":"Fido" },
{ "animal":"cat", "name":"Felix" },
{ "animal":"hamster", "name":"Lightning" }
]
}
and the expected outcome
<li>dog: Fido</li>
<li>cat: Felix</li>
<li>hamster: Lightning</li>
Javascript's for...in functionality loops through the properties of an object, it doesn't increment a variable up to a limit like you expect. Either use it as
for (let i in myObject.pets) which will give i the value of each key in the pets object (with indices in an array acting as keys in an object).
Or since this is a standard array you can do plenty of things with it. You could loop through it normally with for (let i = 0; i < myObject.pets.length; i++) but based on what you're trying to do I recommend reduce.
I've included a demo which uses reduce to get the finalString in a modern JS way. If you want to stick with your current function though, make sure you don't redefine finalString with var finalString in your loop which you are currently doing. My demo doesn't set the innerHTML of an element and instead writes it to the document, but you can do whatever you want with the finalString.
let apiResult = '{"pets":[{ "animal":"dog", "name":"Fido" }, { "animal":"cat", "name":"Felix" }, { "animal":"hamster", "name":"Lightning" } ] }';
let jsonResult = JSON.parse(apiResult);
let finalString = jsonResult.pets.reduce((total, current) => {
return total.concat("<li>" + current.animal + ": " + current.name + "</li>");
}, "");
document.write(finalString);
I really like #Matthew's answer. Here's a version using map instead of reduce, that makes the code more verbose, but I my opinion also easier to read.
const petsString = '{"pets": [{"animal": "dog", "name": "Fido"}, {"animal": "cat", "name": "Felix"}, {"animal": "hamster", "name": "Lightning"}]}'
const petsArray = JSON.parse(petsString).pets
const petsHtml = petsObject
.map(pet => `<li>${pet.animal}: ${pet.name}</li>`)
.join("")
document.write(petsHtml)

Using quotes within a javascript array and getting the result verbatim

So I have an array that looks like:
var typeArray = [
"'<span class="class">Text</span>'",
"test",
]
and im calling the array in code that looks like this:
<script>
var elem = document.getElementById("pHolderGen1");
var num = 151;
for(var i = 1; i <= num; i++) {
var d = document.createElement('div');
d.setAttribute('class', 'pfl');
d.innerHTML = '<p>'
+ typeArray[i-1] +
'</p>';
elem.appendChild(d);
}
</script>
Now I know there is an issue in the array with my use of quotes around class; however when I change it to:
var typeArray = [
"'<span class="/"grass"/">Grass</span>'",
"test",
]
as an attempt to get rid of the qoute issue I'm having all it displays is "NaN."
When I actually run the code I want it to produce (in html):
<p><span class="class">Text</span></p>
So in short I'm looking for a way to fix this and I also want to know why it does this.
Change "'<span class="class">Text</span>'" to "<span class='class'>Text</span>"

Use "event's" output as a variable

I have a problem to manipulate checkbox values. The ‘change’ event on checkboxes returns an object, in my case:
{"val1":"member","val2":"book","val3":"journal","val4":"new_member","val5":"cds"}
The above object needed to be transformed in order the search engine to consume it like:
{ member,book,journal,new_member,cds}
I have done that with the below code block:
var formcheckbox = this.getFormcheckbox();
formcheckbox.on('change', function(checkbox, value){
var arr=[];
for (var i in value) {
arr.push(value[i])
};
var wrd = new Array(arr);
var joinwrd = wrd.join(",");
var filter = '{' + joinwrd + '}';
//console.log(filter);
//Ext.Msg.alert('Output', '{' + joinwrd + '}');
});
The problem is that I want to the “change” event’s output (“var filter” that is producing the: { member,book,journal,new_member,cds}) to use it elsewhere. I tried to make the whole event a variable (var output = “the change event”) but it doesn’t work.
Maybe it is a silly question but I am a newbie and I need a little help.
Thank you in advance,
Tom
Just pass filter to the function that will use it. You'd have to call it from inside the change handler anyway if you wanted something to happen:
formcheckbox.on('change', function(cb, value){
//...
var filter = "{" + arr.join(",") + "}";
useFilter(filter);
});
function useFilter(filter){
// use the `filter` var here
}
You could make filter a global variable and use it where ever you need it.
// global variable for the search filter
var filter = null;
var formcheckbox = this.getFormcheckbox();
formcheckbox.on('change', function(checkbox, value){
var arr = [],
i,
max;
// the order of the keys isn't guaranteed to be the same in a for(... in ...) loop
// if the order matters (as it looks like) better get them one by one by there names
for (i = 0, max = 5; i <= max; i++) {
arr.push(value["val" + i]);
}
// save the value in a global variable
filter = "{" + arr.join(",") + "}";
console.log(filter);
});

How to separate the values from two dimension array in js?

jQuery.get("ChkNewRspLive.php?lastmsgID=" + n, function(newitems){
//some code to separate values of 2d array.
$('#div1').append(msgid);
$('#div2').append(rspid);
});
Let's say the value of newitems is [["320","23"],["310","26"]]
I want to assign "320" and "310" to var msgid.
I want to assign "23" and "26" to var rspid.
How to do that?
I tried to display newitems and the output is "Array". I tried to display newitems[0] and the output is blank.
If I redeclare var newitems = [["320","23"],["310","26"]]; it works. So I guess the variable newitems from jQuery.get is something wrong. Is it I cannot pass the array from other page to current page through jQuery directly?
Regarding the array on other page, if echo json_encode($Arraytest); the output is [["320","23"],["310","26"]] but if echo $Arraytest; the output is Array. How do I pass the array from other page to currently page by jQuery.get?
I don't totally understand the question but I'm going to assume you want the values in an array, as two values can't be stored in one (scalar) variable simultaneously.
jQuery.get("ChkNewRspLive.php?lastmsgID=" + n, function(newitems){
//some code to separate values of 2d array.
var msgid = [],
rspid = [];
for( i = 0 ; i < newitems.length ; i++){
msgid[msgid.length] = newitems[i][0];
rspid[rspid.length] = newitems[i][1];
}
//msgid now contains ["320","310"]
//rspid now contains ["23","26"]
});
Bear in mind those are in the function scope. If you want to use them outside of that scope instantiate them outside. see: closure
You can use pluck from underscore.js: http://documentcloud.github.com/underscore/#pluck
var msgid = _(newitems).pluck(0)
var rspid = _(newitems).pluck(1)
Try this:
function getArrayDimension(arr, dim) {
var res = [];
for(var i = 0; i < arr.length; i++) {
res.push(arr[i][dim]);
}
return res;
}
var newitems = [["320","23"],["310","26"]];
var msgid = getArrayDimension(newitems, 0);
var rspid = getArrayDimension(newitems, 1);
msgid and rspid are arrays holding the 'nth' dimention.
Tnx

Is there an easy way to create dynamic variables with Javascript?

I've built a data-driven google map with different icons that get assigned to the map depending on the type of item located. So if I have 5 types of landmark, and each gets a different icon (store, library, hospital, etc.)-- what I'd like to do is generate the google icon objects dynamically. I was thinking something like this:
types = array('hospital','church','library','store',etc);
var i=0;
while (i<=types.length) {
var landmark + i = new google.maps.Icon();
landmark.image = "icon" + i + ".png";
i++;
}
however, as you've probably guessed, this doesn't work. I also tried using eval, like this:
while (i<=types.length) {
doIcon(i);
i++;
}
function doIcon(i){
eval("var landmark" + i + " = new.google.maps.Icon();");
return eval("landmark" + i);
}
but it didn't work either-- I'd appreciate any pointers on generating javascript variables dynamically. It's got to be pure js, I could do it in PHP but that's not an option here.
Thanks!
It's really easy to do: object["variablename"] = whatever;
So for example you could have an object: var Landmarks = {} and you could add to it like so: Landmarks["landmark" + i] = new google.maps.Icon(); and pass it that way.
If you need these variables to be global (why would you?) you can access the global object directly using window.
If you're going to do it using a declared object such as Landmark["landmark" + i], you really may as well use an index array rather than an associative, it's much easier for iteration. Objects aren't really used with indexed properties because Arrays do a much better job of it:
var myObj = // object version
{
"item0": "blah",
"item1": "blah"
// etc
}
var myArr = // array version
[
"blah",
"blah"
// etc
]
Much more sensible to use the array:
landmarks = []; // new array
types = array('hospital','church','library','store',etc);
var i=0;
while (i<=types.length) {
landmarks.push(new google.maps.Icon());
landmarks[i].image = "icon" + i + ".png";
i++;
}
It makes more sense to do it that way and for...in loops on objects can get a bit messy with prototyped properties being enumerable, etc.
If you're trying to make a variable global, add it to the window object:
var myCustomVar = "landmark" + i;
window[myCustomVar] = new google.maps.Icon();
alert(landmark0);
But this would be polluting the global namespace with many unnecessary variables. So you'd still be better with an array:
window.landmarks = [];
landmarks.push(new google.maps.Icon());
// etc...
Just to answer your question directly (although please note that this is not the solution you want. Check out the other answers. This is just for documentation!), here's a copy-paste from a JavaScript console:
> window["myNamedVar"] = "Hello, World!";
> console.log(myNamedVar);
"Hello, World!"
You'd be better off creating a javascript object which you can use somewhat like an associative array is used in PHP:
var types = ['hospital','church','library','store'];
var landmarks= {};
for (var i in types) {
landmarks[types[i]]= new google.maps.Icon();
landmarks[types[i]].image = "icon" + i + ".png";
}
alert(landmarks['hospital'].image); // displays "icon0.png"
Do you really need those variables? Can't you do with this:
var types = ['hospital','church','library','store'];
for(var i =0; i < types.length; i += 1) (new google.maps.Icon()).image = "icon" + i + ".png";
Modifications done based on comment:
icon name pattern changed from icon + index + .png to icon + type + .png
and saving the results of the loop.
types = ['hospital','church','library','store'];
var landmarks = {};
// images names are of the form icon + type + .png
function createIcon(type)
{
var icon = new google.maps.Icon();
icon.image = "icon" + type + ".png";
return icon;
}
// mapping of landamarks by type and icon
for (var i = 0, len = types.length; i < len; i++)
{
landmarks[types[i]] = createIcon(types[i]);
}
the result is :
{
hospital : icon,
church : icon,
...
}
where icon is a google map icon that has an image attribute that is a string of the form "icon{type}.png" , e.g, iconhostpital.png, iconchurch.png.
To use the icons write landmarks.type where type is one the names in the array of types, e.g. landmarks.hospital.
if the image names are of the form icon + number + .png, and the number for each type is equivalent to its index in the array replace the call createIcon(type[i]) for createIcon(i).

Categories