0

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.

10
  • user['id'] ? should be user[i]
    – Shanimal
    Commented May 23, 2013 at 23:07
  • are you getting a console error? What is L.marker(98.76, 12.34).addTo(map); and why does it have nothing to do with user?
    – km6zla
    Commented May 23, 2013 at 23:07
  • You do know there's a missing ); in the end, right?
    – acdcjunior
    Commented May 23, 2013 at 23:08
  • Still wrong. The last line should be });, not )}.
    – acdcjunior
    Commented May 23, 2013 at 23:13
  • ahhh sorry - no, the user['id'] comes from my database and is an actual user's unique ID - in other words it's totally independent of i here. And L.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!
    – tylerl
    Commented May 23, 2013 at 23:13

2 Answers 2

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']]);
});
1

Solution: Define the array before setting properties to it! Example:

window.userMarkers = new Array();

1
  • 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. Commented May 23, 2013 at 23:41

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.