Javascript仅在页面重新加载后访问对象属性

时间:2016-04-30 16:35:58

标签: javascript google-maps kml geoxml3

我的代码有一个非常奇怪的问题。我使用geoxml3来解析kml文件,它可以解析所有折线,但是当它到达标记时,控制台会说它undefined。奇怪的是,每次我重新加载页面时,它都可以正常工作,但每次我在新选项卡中打开时,它都会再次中断。甚至更奇怪的是,当我在条件之前放置console.log以检查它是否是折线或标记时,浏览器的控制台会显示存在marker属性。

这是我的geoxml3需要的useTheData函数:

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

1 个答案:

答案 0 :(得分:1)

这是由于geoxml3的多边形和kmz分支之间的差异之一。

geoxml3的kmz分支有一个图标的img onload事件处理程序,可能导致它们在解析操作完成后的某个时间才可用。它使图标大小调整更好,但可能导致您在afterParse函数中看到的问题。