2011-11-16 35 views
0

我有一個類MapHandler。CoffeeScript對象屬性和閉包

我創建了一個對象myMaphandler = new MapHandler並調用initialize方法。 但@ userLocationMarker.getPosition()方法返回null :(

如果我從Chrome中JS控制檯評論警報和呼叫@ userLocationMarker.getPosition()我得到必要的座標。

class window.MapHandler 

    initialize: (centerLocation) -> 
    @makeMap(centerLocation) 
    @defineUserLocation() 
    alert @userLocationMarker.getPosition() 


    makeMap: (centerLocation) -> 
    myOptions = 
     zoom: 14 
     center: centerLocation 
     mapTypeId: google.maps.MapTypeId.ROADMAP 
    @map = new google.maps.Map(document.getElementById("map_canvas"), myOptions) 


    placeMarker: (location, icon_path) -> 
    if icon_path 
     markerImage = new google.maps.MarkerImage(icon_path, null, null, null, new google.maps.Size(25, 25)) 
    else 
     markerImage = null 
    marker = new google.maps.Marker(
     position: location 
     map: @map 
     icon: markerImage) 

    defineUserLocation:() -> 
    @userLocationMarker = @placeMarker(null, null) 

    handleMap = (position) => 
     pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude) 
     infowindow = new google.maps.InfoWindow(
     map: @map 
     position: pos 
     content: 'Если это не ваше местоположение - передвиньте маркер' 
    ) 
     @map.setCenter(pos) 
     @userLocationMarker.setPosition(pos) 

    if navigator.geolocation 
     @userPosition = navigator.geolocation.getCurrentPositon(
     handleMap 
    ) 

LINK

爲什麼發生這種情況,什麼我應該避免這種情況做

+0

只是澄清.. console.log(@ userLocationMarker.getPosition())爲您提供正確的數據?我覺得你的文章有些遺漏......你在用圖書館嗎? – Chris

+0

不,它也返回null – rkotov93

+0

好吧,以及getPosition是在哪裏定義的? – Chris

回答

6

初始化@userLocationMarkernull位置:

@userLocationMarker = @placeMarker(null, null) 

然後設置 「真正」 的當前位置在handleMap

handleMap = (position) => 
    #... 
    @userLocationMarker.setPosition(pos) 

其用作getCurrentPosition回調:

if navigator.geolocation 
    @userPosition = navigator.geolocation.getCurrentPosition(
    handleMap 
) 

的問題是,getCurrentPosition是異步的您的alerthandleMap已被getCurrentPosition呼叫之前被呼叫。任何取決於getCurrentPosition所做的事情都必須在handleMap回調中,或者他們需要做好準備處理尚未到達的數據。

您的示例代碼中還存在拼寫錯誤,您在if navigator.geolocation塊中拼寫錯誤getCurrentPosition

當您嘗試從JavaScript控制檯檢查位置時,getCurrentPosition稱爲handleMap@userLocationMarker的位置已正確初始化。

+0

+1。打敗我吧。 :) –

+0

@Trevor:以爲你可能會覺得孤獨囤積所有的CoffeeScript點:) –