2012-08-06 102 views
0

我試圖創建處理谷歌地圖API的跟隨對象後,對象的值越來越不確定:JavaScript對象構建

function GoogleMap(container, mapOptions) { 
    this.Container = container; 
    this.Options = mapOptions; 
    this.Map = new google.maps.Map(document.getElementById(this.Container), this.Options); 

    // Direction 
    this.DirectionService = new google.maps.DirectionsService(); 
    this.DirectionRenderer = new google.maps.DirectionsRenderer(); 
    this.DirectionRenderer.setMap(this.Map); 
    this.DirectionId = 0; 
    this.DirectionResponse = new Array(); 
    this.DrawDirectionDriving = drawDirectionDriving; 
} 

和drawDirectionDriving功能是這樣的:

function drawDirectionDriving(start, end) { 
    var request = { 
    origin: start, 
    destination: end, 
    travelMode: google.maps.TravelMode.DRIVING 
    }; 

    this.DirectionService.route(request, 
    function (response, status) { 
     if (status == google.maps.DirectionsStatus.OK) { 
     this.DirectionRenderer.setDirections(response); 
     this.DirectionResponse[this.DirectionId] = response; 
     this.DirectionId++; 
     } 
     else { 
     alert("Error during drawing direction, Google is not responding..."); 
     } 
    } 
); 
} 

和在某處,我使用這樣的對象:

var myGoogleMap; 

function MapInit() { 
    myGoogleMap = new GoogleMap("divMap", myMapOptions); 
    myGoogleMap.DrawDirectionDriving("İstanbul", "Ankara"); 
} 

Google Map顯示在我的瀏覽器,在構造對象時沒有問題,但在DrawDirectionDriving函數中出錯。

當我在這一行上創建一個斷點時:「myGoogleMap.DrawDirectionDriving(」İstanbul「,」Ankara「);」 「DirectionRenderer」似乎是構造的,但在此行之後(在「Draw」方法之後)DirectionRenderer對象看起來爲空(未定義),因此它出現了像這樣的錯誤「無法獲得setDirections屬性,它是空的bla bla ...」

你能幫我一下嗎?

在此先感謝...

+0

我不知道谷歌地圖API,但我看不出在'drawDirectionDriving'函數返回語句因此推測它返回undefined,反正你」不要在'drawDirectionDriving'函數中使用新單詞,所以'this'不指向'drawDirectionDriving'函數。 – DavidHyogo 2012-08-06 22:11:35

+0

我的問題可能是你正在談論的這個問題,但是DrawDirectionDriving必須是一個方法,並且可能會被錯誤地實現。方法必須像這樣實現,或者這是一種變量賦值。它是否將DrawDirectionDriving的返回值分配給DrawDirectionDriving變量? – 2012-08-06 22:19:05

回答

2

this keyword確實點到別的在route回調函數的東西。它的DirectionRenderer屬性解析爲null/undefined,並從中獲取setDirections屬性將導致該異常。

使用解引用變量:

function drawDirectionDriving(start, end) { 
    var request = { 
    origin: start, 
    destination: end, 
    travelMode: google.maps.TravelMode.DRIVING 
    }; 
    var that = this; 

    this.DirectionService.route(request, 
    function (response, status) { 
     if (status == google.maps.DirectionsStatus.OK) { 
     that.DirectionRenderer.setDirections(response); 
     that.DirectionResponse[this.DirectionId] = response; 
     that.DirectionId++; 
//  ^^^^ points to the GoogleMap instance 
     } 
     else { 
     alert("Error during drawing direction, Google is not responding..."); 
     } 
    } 
); 
} 
+0

是的,這是答案,非常感謝。 – 2012-08-06 22:23:11