我正在使用 Phonegap、Backbone.js、Require.js 和 PageSlider (https://github.com/ccoenraets/PageSlider) 创建一个移动应用程序。
我想用标记显示一个简单的谷歌地图。模板如下所示:
<div class='main-content' id='map-container'>
<a href="geo:51.903679,-8.468274">
<div id="map-canvas"></div>
</a>
</div>
这是 View :
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是应用程序的链接。当您单击“位置”时, map 会完美呈现。但是,当您导航到其他任何地方,然后返回位置时,在左上角只能看到 map 的一小部分。
我试过做,有人建议here :
google.maps.event.trigger(map, 'resize').
但无济于事。有任何想法吗?
最佳答案
您的 View 适用于未附加到 DOM 的节点,因此没有大小,a situation Google Map is not very fond of .这是您的路由器,通过 PageSlider
,这确实会在您的渲染功能发生后附加节点。
这是您的困境的演示:http://jsfiddle.net/3C7g3/
您有几种选择来解决它:
google.maps.event.trigger(map, 'resize')
之后 节点被插入到 DOM 中(这段代码对应于 map 的路由器条目)// 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/
view.initialize
中删除渲染。并调用 view.render
在 container.append(page);
之后在您的 slidePageFrom
方法。http://jsfiddle.net/3C7g3/2/
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/
关于google-maps - 使用 Backbone.js 首次查看后,Google map 无法正确呈现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19976662/