0

If I build an array of objects.

var destinations = [{
  id:   '277',
  title:'Alicante',
  lat:  '38.35782',
  lng:  '-0.5425632',
  content:  '<p>string</p>'
},{
  id:   '275',
  title:'Amsterdam',
  lat:  '52.3745292',
  lng:  '4.7585347',
  content:  '<p>string</p>'
},{
  id:   '250',
  title:'Belfast',
  lat:  '36.1673368',
  lng:  '27.6853392',
  content:  '<p>string</p>'
}, {
  id:   '263',
  title:'Bergerac',
  lat:  '44.8519854',
  lng:  '0.4532777',
  content:  '<p>string</p>'
}]

How do I use a loop and use the data to create variable names and properties? What is the function that would iterate through the array and create variables (which I am using to populate a Google Map). I am reading through so many code examples but I can't seem to get it right.

I would expect the following function to create four variables (marker277, marker275, marker250, marker263), with position taken from objects in the array in a similar fashion, but it doesn't work.

for (var i = 0, l = destinations.length; i < l; i++) {
  var obj = destinations[i];
  var marker[obj.id] = new google.maps.Marker({
    position: {lat: obj.lat, lng: obj.lng}
  });
}

Thank you in advance for your help.

Rhecil Codes
  • 511
  • 4
  • 24
  • The only problem i can see with your code that it does not return anything. You declared marker inside for loop. But should be outside and initialized as an array. Better to use hashmap as your ids are not regular. – Mikhail Chibel Jun 29 '16 at 01:03
  • http://stackoverflow.com/questions/2413414/is-there-an-easy-way-to-create-dynamic-variables-with-javascript – Paul Jun 29 '16 at 01:09

2 Answers2

0

Well, I think the marker lat long expect float values, so you should try using parseFloat(). Also you should store the marker in an array to keep it, like this.

var markers = [];
for (var i = 0, l = destinations.length; i < l; i++) {
  var obj = destinations[i];
  var lat = parseFloat(obj.lat);
  var long = parseFloat(obj.lng);
  markers[obj.id] = new google.maps.Marker({
    position: {lat: lat, lng: long}
  });
}
Nguyen Tuan Anh
  • 1,036
  • 8
  • 14
0

Your code does not create variable names but tries to set marker to the array marker. You most likely want to have map of markers

var markers = {};
for (var i = 0, l = destinations.length; i < l; i++) {
  var obj = destinations[i];
  markers[obj.id] = new google.maps.Marker({
    position: {lat: obj.lat, lng: obj.lng}
  });
}
Mikhail Chibel
  • 1,865
  • 1
  • 22
  • 34