I'm trying to generate markers for every user in my $.each loop in such a way that I can select each marker using the corresponding userId of a given user.
$.each($.parseJSON(window.usersArray), function (i, user) {
window.userMarkers[user['id']] = L.marker(98.76, 12.34).addTo(map);
console.log(window.userMarkers[user['id']]);
});
EDIT
I get the error:
Cannot set property '3' of undefined, where 3 is the user's ID.
asked May 23, 2013 at 23:05
tylerl
1,1802 gold badges20 silver badges41 bronze badges
2 Answers 2
You need to create the object (or array depending on your needs) before you can add anything to it.
window.userMarkers = {};
$.each($.parseJSON(window.usersArray), function (i, user) {
window.userMarkers[user['id']] = L.marker(98.76, 12.34).addTo(map);
console.log(window.userMarkers[user['id']]);
});
answered May 23, 2013 at 23:39
James Montagne
78.9k14 gold badges115 silver badges132 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Solution: Define the array before setting properties to it! Example:
window.userMarkers = new Array();
answered May 23, 2013 at 23:40
tylerl
1,1802 gold badges20 silver badges41 bronze badges
1 Comment
James Montagne
Don't use
new Array() use []. Also, if the keys can be non-numeric or are very sparse, you probably want to use an object instead as in my answer using {} to initialize it.lang-js
L.marker(98.76, 12.34).addTo(map);and why does it have nothing to do withuser?);in the end, right?});, not)}.user['id']comes from my database and is an actual user's unique ID - in other words it's totally independent ofihere. AndL.marker(98.76, 12.34).addTo(map);is just the code that adds the marker to the map in Leaflet - I wasn't sure if I should remove it or not. And yes, you're right, I forgot the);, added it in. Validating from now on!