2013-11-14 33 views
4

進出口創造與PhoneGap的,Backbone.js的,Require.js和PageSlider(https://github.com/ccoenraets/PageSlider)移動應用首次觀看後正確顯示。谷歌地圖不Backbone.js的

我想用一個標誌來顯示一個簡單的谷歌地圖。該模板的樣子:

<div class='main-content' id='map-container'> 

    <a href="geo:51.903679,-8.468274"> 
     <div id="map-canvas"></div> 
    </a> 

</div> 

這裏是視圖:

define(function (require) { 

"use strict"; 

var $     = require('jquery'), 
    _     = require('underscore'), 
    Backbone   = require('backbone'), 
    tpl     = require('text!tpl/Map.html'), 
    side_nav    = require('text!tpl/SideNav.html'), 
    template = _.template(tpl), 
    map, myLatlng, mapOptions, marker; 


return Backbone.View.extend({ 

    initialize: function() {   
     this.render();  
    }, 

    initMap: function() { 

     myLatlng = new google.maps.LatLng(51.903679, -8.468274); 

     mapOptions = { 
      center: myLatlng, 
      zoom: 12, 
      mapTypeId: google.maps.MapTypeId.ROADMAP 
     }; 

      map = new google.maps.Map(this.$el.find('#map-canvas')[0], 
             mapOptions); 


     marker = new google.maps.Marker({ 
      position: myLatlng, 
      map: map, 
      title: 'Christians Brothers College Cork' 
     }); 

    }, 

    render: function() { 
     this.$el.html(template({side_nav:side_nav})); 
     this.initMap();  
    }, 


}); 

}); 

Here是對應用程序的鏈接。當你點擊「位置」時,地圖呈現完美。但是,當你瀏覽其他地方,然後回到位置,只有在地圖的一小部分,可以在左上角看到。

我想這樣做,這是建議here

google.maps.event.trigger(map, 'resize'). 

,但無濟於事。有任何想法嗎?

回答

6

您的視圖適用於未附加到DOM的節點,因此沒有大小,a situation Google Map is not very fond of。這是你的路由器,通過PageSlider,這並不追加該節點已發生渲染功能之後。 這裏是你的困境的一個演示:http://jsfiddle.net/3C7g3/

您有幾種選擇來解決這個問題:

  • 呼叫google.maps.event.trigger(map, 'resize')後的節點插入DOM(這段代碼對應於你的路由器條目地圖)

    // assuming you stored the map object in your view 
    require(["app/views/Map"], function (Map) { 
        var view = new Map(); 
        slider.slidePage(view.$el); 
        google.maps.event.trigger(view.map, 'resize'); 
    }); 
    

    http://jsfiddle.net/3C7g3/1/

  • 調用render之前插入節點到DOM。在你的情況下,這可能意味着從view.initialize中刪除渲染,並在slidePageFrom方法中的container.append(page);之後調用view.render

    http://jsfiddle.net/3C7g3/2/

  • 更hackish的方式將是暫時的元素從DOM

    initMap: function() { 
        // assuming a temp class that hides the element. For example, 
        // .temp {position: absolute; visibility:hidden; } 
        this.$el.addClass('temp'); 
        $('body').append(this.$el); 
        // ... 
        this.$el.remove(); 
        this.$el.removeClass('temp'); 
    } 
    

    http://jsfiddle.net/3C7g3/3/

+0

添加到DOM,應用谷歌地圖,然後將其刪除多麼輝煌而全面的答案,謝謝! – user1716672

+0

如果您在地區使用MarionetteJS,則在onShow方法內創建地圖而不是在onRender中解決問題,因爲視圖已經在DOM中。我真的建議木偶,這樣可以節省很多的麻煩。 – alancasagrande