javascriptgoogle-mapskmlgeoxml3

Javascript only access object property after page reload


I'm have a pretty weird problem with my code. I'm using geoxml3 to parse a kml file, and it parses all the polylines ok, but when it gets to the markers, the console says it's undefined. The weird part is that every time I reload the page, it works fine, but every time I open in a new tab, it breaks again. Even weirder, when I put a console.log right before the condition to check if it's a polyline or a marker, the browser's console shows there to be a marker property.

Here's my useTheData function that geoxml3 requires:

function useTheData(doc){
console.log("Starts Parse");
console.log(doc[0].placemarks.length);  
for (var i = 0; i < doc[0].placemarks.length; i++){
    console.log("i: "+i+", placemark:");    
    console.log(doc[0].placemarks[i]); //here the .marker property exists in the console
    console.log(".marker:");
    console.log(doc[0].placemarks[i].marker); //here it says it's undefined!
    if(doc[0].placemarks[i].polyline){ //check if it's a polyline
        google.maps.event.addListener(doc[0].placemarks[i].polyline, 'click', select_option);
    }
    else{
        console.log("### i = "+i);
        console.log("1");
        console.log(doc[0].placemarks[i].marker); //here, the exact same object, doesn't have the marker property!
        console.log("2");
        google.maps.event.addListener(doc[0].placemarks[i].marker, 'click', select_option); //Because of that, the first time the page loads, it get's stuck in the function cuz it can't access the .marker
        console.log("3");
        doc[0].placemarks[i].marker.setIcon({
            url: "img/bola.png",
            scaledSize: new google.maps.Size(10, 10),
            anchor: new google.maps.Point(5, 5)
        });
        console.log("4");
    }
}
console.log("End Parse");
google.maps.event.addListener(map, 'click', select_option);
}   

Solution

  • This is due to one of the differences between the polys and kmz branches of geoxml3.

    The kmz branch of geoxml3 has an img onload event handler for icons that can cause them not to be available until sometime after the parse operation is finished. It makes the icon sizing work better, but can cause issues like you see in the afterParse function.