2015-02-24 94 views
1

首先代碼:如何重新渲染灰燼成分與谷歌地圖

我創建這使得谷歌地圖V3地圖像灰燼成分:

App.GoogleMapsComponent = Ember.Component.extend(
classNames: ['ember-view-map'] 

insertMap: (-> 
    @getUserLatLng() 
    options = 
    center: new google.maps.LatLng(
     @get('latitude'), 
     @get('longitude') 
    ) 
    zoom: 14 
    draggable: false 
    zoomControl: false 
    panControl: false 
    streetViewControl: false 
    scaleControl: false 
    mapTypeControl: false 
    scrollwheel: false 
    disableDoubleClickZoom: true 
    mapTypeId: google.maps.MapTypeId.ROADMAP 

    @set 'map', new google.maps.Map(@$('.map-container')[0], options) 
    @set 'markerCache', [] 
    @coordinatesChanged() 
    @setMarkers() 
).on('didInsertElement') 

getUserLatLng: -> 
    self = @ 
    if [email protected]('latitude') || [email protected]('longitude') 
    $.ajax 
     url: '//ipinfo.io/json', 
     success: (response) -> 
     self.set('latitude', response.loc.split(',')[0]) 
     self.set('longitude', response.loc.split(',')[1]) 
     , 
     dataType: 'json' 

coordinatesChanged: (-> 
    map = @get('map') 
    if map 
    map.setCenter new google.maps.LatLng(@get('latitude'), @get('longitude')) 
    map.setZoom map.getZoom() 
    google.maps.event.trigger(map, 'resize') 
    return 
).observes('latitude', 'longitude') 

組件模板是:

.map-wrapper 
    .map-container 

我用它在其他出口,如:

.row.row-map 
.col-md-12.col-map 
    google-maps latitude=location.latitude longitude=location.longitude markers=markers 

問題和場景

  1. 第一種情形

這個出口被路由到我的「/」,現在如果我從瀏覽器中輸入URL使這個頁面就呈現此組件就好了。

  • 第二種情況
  • 我訪問其他頁面中應用,並使用link-to鏈接過渡到我的「/」,谷歌地圖組件呈現罰款。

  • 第三個場景(有問題
  • 我參觀 '/',過渡到使用link-to其他頁面比方說about頁,並從那裏我回去'/'也使用link-to鏈接。然後組件不能正確渲染。

    我可以看到適當的DOM元素,但谷歌地圖沒有調整到全屏寬度/高度它顯示地圖的只有一層在左上角,如:

    failure when re-rendering map

    所以出現問題時,我嘗試重新渲染組件,因爲當它第一次渲染時看起來很好。我認爲組件在轉換到其他路由時完全被破壞,當我嘗試在控制檯中記錄此對象時它看起來像它,它在轉換到路由而不是'/'之後未定義。

    回答

    0

    發現了它,一直在尋找在錯誤的地方:) 的問題是在coordinatesChanged功能,我試圖觸發調整的谷歌地圖功能時if map情況是真實的,但在過渡我已經爲成分被破壞和重新渲染再次獲取緯度/經度,所以我用undefined座標調整了地圖的大小。固定功能看起來像:

    coordinatesChanged: (-> 
        if @get('map') && @get('latitude') && @get('longitude') 
        @get('map').setCenter new google.maps.LatLng(@get('latitude'), @get('longitude')) 
        @get('map').setZoom @get('map').getZoom() 
        google.maps.event.trigger(@get('map'), 'resize') 
    ).observes('latitude', 'longitude') 
    

    所以乾脆我當map對象存在和座標被定義調整。

    1

    如果你有選擇,而不是滾動自己的,我會建議使用Ember Google Map組件,因爲它似乎做你所需要的。它可以通過npm:npm i ember-google-map獲得。如果這不是你的衚衕,那麼你可以挖掘源代碼,看看需要什麼才能正確地重新渲染地圖。

    +0

    謝謝,爲了回答Oren,我不是使用外部附加組件/ gem作爲非常簡單的組件的忠實粉絲,我想要的是帶有標記的簡單映射,因此在寫入時會更容易維護我自己的。從我查過的Ember谷歌地圖插件看起來很棒,但它在我的情況下是複雜的。 – 2015-02-24 22:10:01