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.

2
  • 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. Commented Jun 29, 2016 at 1:03
  • stackoverflow.com/questions/2413414/… Commented Jun 29, 2016 at 1:09

2 Answers 2

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}
  });
}
Sign up to request clarification or add additional context in comments.

Comments

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}
  });
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.