Reputation: 91
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
Upvotes: 2
Views: 170
Reputation: 1971
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.
Upvotes: 3
Reputation: 27174
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);
Upvotes: 3
Reputation: 25351
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/>");
}
Upvotes: 1