-1

is the first time that I use OOP in Javascript, called markerPlaces that have some data in it:

enter image description here

I want to access to the property lat for each node via for statement: I tried:

for(i=0;i<markerPlaces.length;i++){
    console.log(markerPlaces[i][lat]);
}

But it doesn't work. The error is "lat is undefined".

The complete function is:

function initialize(markerPlaces) {
    (function(window, google, maplib){
        var mapOptions = maplib.MAP_OPTIONS,
        domElement = document.getElementById('map'),
        //map declaration
        map = new google.maps.Map(domElement, mapOptions);
        console.log(markerPlaces);
        //for statement for markers
        for(i=0;i<markerPlaces.length;i++){
            console.log(markerPlaces[0].posts.lat);
        }
        markers = new google.maps.Marker({
                position: {
                    lat:45.0690246,
                    lng:7.6932346
                },
                map: map,
                icon: 'http://example.com/wp-content/themes/turisti/img/poi.png'
            })
    }(window, google, window.maplib || (window.maplib = {})));
}

but firebug result is:

enter image description here

ghost
  • 45
  • 1
  • 5
  • 4
    try markerPlaces[i].lat – prawn Oct 23 '14 at 15:30
  • It seems `markerPlaces` is a an array with a single element. I believe you actually have to iterate over `markerPlaces[0].posts`. – Felix Kling Oct 23 '14 at 16:21
  • i edit the for statement, you mean in this way? – ghost Oct 23 '14 at 16:34
  • No. As I said, you have to **iterate** over `markerPlaces[0].posts`. I.e. `for (var i = 0; i < markerPlaces[0].posts.length; i++) { /* do something with markerPlaces[0].posts[i] */ }`. Or make it simpler by assigning `var posts = markerPlaces[0].posts;` first. If you are unfamiliar with arrays and objects, I recommend to read the MDN JavaScript Guide: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Predefined_Core_Objects#Array_Object . FYI, this has nothing to do with OOP. – Felix Kling Oct 23 '14 at 16:55

1 Answers1

1

You can access it via:

for (var i = 0; i < markerPlaces.length; i++)
{
    console.log(markerPlaces[i].lat);
    // or
    console.log(markerPlaces[i]["lat"]);
}

Make sure you put the var keyword before i = 0 in your for loop as well.

Matt
  • 1,377
  • 2
  • 13
  • 26