又一次在javascrit 中遇到因為變量範圍而苦惱了几日(對上是年多前做GP1,首次體會到var的影响, 但無寫低, 唔記得詳細code)
今次又是google map下(api v3) 引用一個例子略加修改, 目的想加一個infowindow(一開始彷照 var center_market 建立), 然後過一段時間自動關閉(setTimeout()), 但總是出現"infowindow is undefined", 經過嘗試, 想信是variable scope問題, 用第一種程序編寫 "//@@"部份, 把 infowindow 變成全域變量, 讓setTimeout可以找得到, 但就結構而言, 會較混亂. 於是試第二種(下面程序未註的碼). 這種較符合原來的結構, 且較清晰( 雖然infowindow 依然是全域變量). 關鍵在於建立infowindow = new google.map.InfoWindow();時, 勿加入var (本域變量Local Variable). 但奇怪的是同樣的center_mark卻没問題, 難道是之後没有引用
另外在測試期間, 在各處加入"this", 但無助解決問題.
程序如下:((大致結構)
<_script>
//@@ var infowindow = new google.map.InfoWindow();
function DistanceWidget(map){
//一開始彷照 var center_market 建立
var center_marker = new google.maps.Marker({ ... });
// Bind the marker map property to the DistanceWidget map property
center_marker.bindTo('map', this);
....
....
//設為全域變量,不可在之前加var, 否則找不到.
infowindow = new google.maps.InfoWindow();
inforwindow.setOption(....); //在DistanceWidget()內不可加this,
infowindow.open(map, center_marker);
....
} //end DistanceWidget();
DistanceWidget.prototype = new google.maps.MVCObject();
//新加的method
DistanceWidget.prototype.autoclose_info = function(){
setTimeout("this.infowindow.close()",20000); //加不加this, 無影响.
}
function init(){
....
....
distanceWidget = new DistanceWidget();
distanceWidget.autoclose_info();
//@@ setTimeout("distanceWidget.infowindow.close()", 20000);
//@@即使用OO語法寫明distanceWidget都是"is undefined"
} //end init();
google.maps.event.addDomListener(window, 'load', init);
//@@ setTimeout("infowindow.close()", 20000);
<_/script>
other html code
http://code.google.com/intl/zh-TW/apis/maps/articles/mvcfun.html
http://www.mredkj.com/tutorials/reference_js_intro.html#scope
Tuesday, May 03, 2011
Subscribe to:
Post Comments (Atom)
3 comments:
setTimeout用法示例
http://www.takka.com.hk/jstutor/ch10/ch10.htm
有理由相信呢個問題是同我對google map MVC 理解不夠有關. 當然, 不懂javascript 亦是主因
http://blog.wctang.info/2009/06/google-maps-api-v3-mvcobject.html
Post a Comment