I have this code, which works pretty well :
var draw = [
{lat:60.06484046010452,lng:-121.640625}, {lat:50.064191736659104,lng:-136.40625}, {lat:50.958426723359935,lng:-103.7109375}
];
But Now, as the Values of the Variable draw needs to be changed at the runtime, I Wrote this code & I expect it allow changing draw values as the Values of the variable st changes :
var st = "{lat:60.06484046010452,lng:-121.640625},{lat:50.064191736659104,lng:-136.40625},{lat:50.958426723359935,lng:-103.7109375}";
var draw =[ st ];
But this isn't working, How can i make it work, I'm a noob, thank you
st is of type String, you can only manipulate it as a text would be.
I believe you are using objects wrong but you were using it right initially:
var draw = [{lat:60.06484046010452,lng:-121.640625}, {lat:50.064191736659104,lng:-136.40625}, {lat:50.958426723359935,lng:-103.7109375}];
Furthermore if you need to add objects to this array use the push method.
draw.push({ lat: 60.06484046010452, lng: -103.7109375 });
To remove from the end use the pop method:
var lastItem = draw.pop();
To add at the beginning use the unshift method and to remove use shift.
You just turned your object into a string. Just keep it as an object, and it will work fine (a.k.a remove the quotes):
var st = '[{"lat":60.06484046010452,"lng":-121.640625},{"lat":50.064191736659104,"lng":-136.40625},{"lat":50.958426723359935,"lng":-103.7109375}]';
var draw = JSON.parse(st);
Your original code works and you can edit it. The draw variable will be a list of objects and you can add and delete items:
var draw = [
{lat:60.06484046010452,lng:-121.640625}, {lat:50.064191736659104,lng:-136.40625}, {lat:50.958426723359935,lng:-103.7109375}
];
draw.push({lat:10.10101010,lng:20.20202020});
for(var i = 0; i < draw.length; i++){
document.write(draw[i].lat + " / " + draw[i].lng + "<br/>");
}
Related
I am Facing this Problem, my randomPoints array element is getting replaced by push method.
Here is the output of my Console
I don't know why this is happening but if I don't use randomPoint.add, it dosen't replaces and work fine.
randomPoint.add retuns the same Vector object as it would return without it.
var hw
var center
var randomPoints = []
var pointWidth = 20
var points = 300
centerCircleWidth = 300;
pointsOffset = 10
function setup(){
hw = createVector(600,500)
createCanvas(hw.x,hw.y)
center = createVector(hw.x/2,hw.y/2)
var randomPoint = createVector(0,0)
randomPoints.push(randomPoint)
randomPoint = p5.Vector.fromAngle(-radians(120), random(centerCircleWidth/2-pointWidth,centerCircleWidth/2-pointsOffset))
randomPoints.push(randomPoint)
console.log(randomPoint)
randomPoint = randomPoint.add(p5.Vector.fromAngle(radians(60), random(pointsOffset,2*pointsOffset)))
// this here replaces the last element of array by itself and add another element of same type.
randomPoints.push(randomPoint)
console.log(randomPoint)
console.log(randomPoints)
}
function draw(){
translate(center.x, center.y)
background(51);
strokeWeight(0)
fill(255)
ellipse(0,0, centerCircleWidth, centerCircleWidth)
for(i=0;i<randomPoints.length;i++){
fill(10)
ellipse(randomPoints[i].x,randomPoints[i].y,pointWidth,pointWidth)
}
}
Your problems looks to be an object reference problem. The third push isn't replacing the previous element in the array, but you are updating the reference which the array is holding, therefore the element in the array is being updated.
If you remove the third push, you will see that the second item in the array will still be updated.
What you need to do is either create a copy of randomPoint and then make a change to it, or create a new variable.
Take a look at this SOF answer which should make it clearer.
I'm trying to merge multiple arrays evenly/alternating in javascript/Google appScript. There are several arrays (5 or 6). I've tried 2 different methods, but neither worked. I don't work a lot with javascript honestly and I've managed to get the code to this point, but I can't get it merge properly; and most of them said merging two arrays to one (might be my problem).
I've seen plenty on php examples that were on how to do this and they are pretty straight forward in logic reading and I understand them better, but all javascript methods I've looked at and tried so far have failed to produce the results I want. I'm not sure if it's the way AppScript is formatting the arrays or they're just no made to handle more that 2.
My data looks similar to this at the moment:
var title = ["sometitle1","sometitle2","sometitle3"];
var link = ["somelink1","somelink2","somelink3"];
var date = ["somedate1","somedate2","somedate3"];
var data = ["somedata1","somedata2","somedata3"];
var all = [title,link,date,data];
var mix = [];
Note: all the variable data will/should be the same length since the data is being pulled from a spreadsheet.
My desired output is:
mix = ["sometitle1","somelink1","somedate1","somedata1","sometitle2","somelink2","somedate2","somedata2","sometitle3","somelink3","somedate3","somedata3"];
I tried using appscript to merge them with this: return ContentService.createTextOutput(title + link + data + date), but it didn't work out properly, it printed them in that order instead of merging the way I'd like them too.
Then I tried using a loop merge that I found here on sstackoverflow:
for (var i = 0; all.length !== 0; i++) {
var j = 0;
while (j < all.length) {
if (i >= all[j].length) {
all.splice(j, 1);
} else {
mix.push(all[j][i]);
j += 1;
}
}
}
But it splice merges every letter with a comma
mix = [s,o,m,e,t,i,t,l,e,1,s,o,m,e,t,i,t,l,e,2,s,o,m,e,t,i,t,l,e,3,s,o,m,e,l,i,n,k,1,...]
and doesn't alternate data either.
The code (2 version) I'm working on is: here with Output
&
Here with Output
(Also, dumb question, but do I use title[i] + \n OR title[i] + "\n" for adding new lines?)
Use a for loop and the push() method like this :
function test(){
var title = ["sometitle1","sometitle2","sometitle3"];
var link = ["somelink1","somelink2","somelink3"];
var date = ["somedate1","somedate2","somedate3"];
var data = ["somedata1","somedata2","somedata3"];
//var all = [title,link,date,data];
var mix = [];
for(var n=0;n<title.length;n++){
mix.push(title[n],link[n],date[n],data[n]);
}
Logger.log(JSON.stringify(mix));
}
And also : title[i] + "\n" for adding new lines
Edit following comments :
Your code should end like this :
...
for(var n=0;n<titles.length;n++){
mix.push(titles[n],links[n],descriptions[n],pubdates[n],authors[n]);
}
var mixString = mix.join('');// convert the array to a string without separator or choose the separator you want by changing the argument.
//Print data and set mimetype
return ContentService.createTextOutput(mixString)
.setMimeType(ContentService.MimeType.RSS);
}
I have 5 information coming at the same time like "long", "lat", "speed", "immat", and "date". At first, every 0.1 second new 5 of the info comes in for as long as info still available, then each time another set of the new 5 info available, another round of the same thing happen. I would like to know how to temporary keep all this values and display it.
var myPin = Table_Pins[immat];
myPin.Lat[i] = document.getElementById("Lat");
myPin.Long[i] = document.getElementById("Long");
myPin.immat[i] = document.getElementById("immat");
myPin.date[i] = document.getElementById("date");
myPin.speed[i] = document.getElementById("vitesse");
for (i=0; i<myPin.length; i++){
document.write("lat=" +myPin.Lat[i]);
document.write("long=" +myPin.Long[i]);
document.write("immat=" +myPin.immat[i]);
document.write("date=" +myPin.date[i]);
document.write("speed=" +myPin.speed[i]);
}
Use Object to store data inside an Array:
var pins = []; //this will contain a list of your objects, it's better than keeping an object containing arrays
//inside your function that stores data you will have this
var pin = {
lat: document.getElementById('Lat'),
long: document.getElementById('Long'),
immat: document.getElementById('immat'),
date: document.getElementById('date'),
speed: document.getElementById('vitesse')
};
pins.push(pin);
//and after pushing it you could add to DOM dynamically without looping over al the pins
Assuming that you have a <ul> with id="pins" you can do something similar(just after the pins.push(pin)):
var pinUl = document.getElementById('pins'); //you can declare this after pins
//and now the code that adds an element to the HTML page
var pinLi = "<li>" + JSON.stringify(pin) + "</li>";
pinUl.innerHTML += pinLi; //append the pin at the end of the other
See this example
Remember to avoid document.write!
it's just a problem of global and local variance.Avoid defined var map in function when already defined var map = null in global. Only "map"is enough without "var" in a function.
This is annoying me.
I'm setting an array in beginning of the doc:
var idPartner;
var myar = new Array();
myar[0] = "http://example.com/"+idPartner;
And I'm getting a number over the address, which is the id of partner. Great. But I'm trying to set it without success:
$.address.change(function(event) {
idPartner = 3;
alert(idPartner);
}
Ok. The alert is giving me the right number, but isn't setting it.
What's wrong?
Changing the value of the variable does not re-set the values within the array. That is just something javascript can't do automatically. You would have to re-generate the array for it to have the new id. Could you add the id to the value where you use the array instead of pre-setting the values in the array containing the id?
Edit: For example, you would do:
var myArray = [];
var myId = 0;
myArray[0] = "http://foo.com/id/";
and when you need to use a value from the array, you would do this:
var theVal = myArray[0] + myId;
Try this:
var myvar = ["http://site.com/"];
$.address.change(function(event) {
myvar[1] = 3;
}
then use myvar.join () where you need the full url.
The problem here is that at the line
myar[0] = "http://site.com/"+idPartner;
..you perform a string concatenation, meaning you copy the resulting string into the array at index position 0.
Hence, when later setting idPartnerit won't have any effect on the previously copied string. To avoid such effect you can either always construct the string again when the idPartnervariable updates or you create an object and you evaluate it when you need it like...
var MyObject = function(){
this.idPartner = 0; //default value
};
MyObject.prototype.getUrl = function(){
return "http://site.com/" + this.idPartner;
};
In this way you could use it like
var myGlblUrlObj = new MyObject();
$.address.change(function(event){
myGlblUrlObj.idPartner = ... /setting it here
});
at some later point you can then always get the correct url using
myGlblUrlObj.getUrl();
Now obviously it depends on the complexity of your situation. Maybe the suggested array solution might work as well, although I prefer having it encapsulated somewhere in an object for better reusability.
myar[0] = "http://site.com/" + idPartner;
After this line, myar[0] = "http://site.com/undefined" and it has nothing to do with the variable idPartner no more.
So, after that changing the value of idPartner will affect the value of myar[0].
You need to change the value of myar[0] itself.
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).