使用Backbone.js进行第一次查看后,Google地图无法正确呈现

use*_*672 4 google-maps google-maps-api-3 backbone.js

我正在使用Phonegap,Backbone.js,Require.js和PageSlider(https://github.com/ccoenraets/PageSlider)创建移动应用程序.

我想用标记显示一个简单的Google Map.模板看起来像:

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

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

</div>
Run Code Online (Sandbox Code Playgroud)

这是观点:

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();       
    },


});

});
Run Code Online (Sandbox Code Playgroud)

是应用程序的链接.当您单击"位置"时,地图呈现完美.但是当你在其他任何地方导航,然后返回到位置时,只能在左上角看到地图的一小部分.

我试过了,这里建议:

google.maps.event.trigger(map, 'resize').
Run Code Online (Sandbox Code Playgroud)

但无济于事.有任何想法吗?

nik*_*shr 6

您的视图适用于未附加到DOM的节点,因此没有大小, Google Map不太喜欢这种情况.您的路由器via PageSlider,它会在您的渲染功能发生后附加节点.以下是您的困境演示:http://jsfiddle.net/3C7g3/

您有几种方法可以解决它:

  • 将节点插入DOM google.maps.event.trigger(map, 'resize') 调用(此位代码对应于映射的路由器条目)

    // 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');
     });
    
    Run Code Online (Sandbox Code Playgroud)

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

  • 在调用render之前将节点插入DOM.在您的情况下,这可能意味着从您的方法中删除渲染view.initialize并调用view.renderafter .container.append(page);slidePageFrom

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

  • 一种更为hackish的方式是暂时将元素添加到DOM,应用Google Maps,然后将其从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');
    }
    
    Run Code Online (Sandbox Code Playgroud)

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