Reputation: 465
Am working on Google Maps, I have a problem in creating an array of objects, and a variable holds it(array of objects) for later processing.
var lat=new Array("12.996188333333","12.988683333333","12.99156","13.092916666667");
var lng=new Array("77.58392","77.57781","78.579193333333","77.594161666667");
var latlng = [ new google.maps.LatLng( lat[0], lng[0] ) ,
new google.maps.LatLng( lat[1], lng[1]),
new google.maps.LatLng( lat[2], lng[2] ),
new google.maps.LatLng( lat[3],lng[3] )];
so, latlng holds objects in array.This is a case where array lat and array lng are declared(static).What if its dynamic,say i have the count, but how do i create a dynamic array of objects. I tried to loop it, but no results.Please help!!!
for(var i=0;i<3;i++)
{
var latlng=new Array();
latlng[i]= new google.maps.LatLng(lat[i],lng[i]);
}
console.log(latlng) gives me: [undefined,undefined,undefined,{13.092916666667,77.594161666667}]
Upvotes: 1
Views: 573
Reputation: 707816
You can do it like this:
var latlng = [];
for (var i=0; i<3; i++)
{
latlng.push(new google.maps.LatLng(lat[i],lng[i]));
}
You needed to move the declaration of the array outside the loop so it's initialized once and then you add an item onto the end of the array each time through the loop.
You also don't have to hard code the length either:
var latlng = [];
for (var i = 0; i < lat.length; i++)
{
latlng.push(new google.maps.LatLng(lat[i],lng[i]));
}
Upvotes: 0
Reputation: 4079
put the var latlng=new Array();
outside the for
loop. at the moment, you're clearing the array every time you loop.
Upvotes: 0
Reputation: 215019
var lat = ["12.996188333333","12.988683333333","12.99156","13.092916666667"];
var lng = ["77.58392","77.57781","78.579193333333","77.594161666667"];
var latlng = [];
for (var i = 0; i < lat.length; i++)
latlng[i] = new google.maps.LatLng(lat[i], lng[i]);
(assuming lat and lng have the same length).
Upvotes: 3