我正在學習骨幹,我開始構建使用谷歌地圖的應用程序。我的問題是,當我試圖使谷歌地圖在我看來沒有任何反應,只出現一個包含灰色id="map_canvas"
的div
,就像這樣:渲染谷歌地圖backbonejs
,並在我的控制檯登錄我有這樣的錯誤Uncaught TypeError: Cannot read property 'setCenter' of undefined
代碼我的觀點:
ev.views.Home = Backbone.View.extend({
map: null,
pos: null,
initialize: function(){
this.template = _.template(ev.templateLoader.get('home'));
this.render();
},
initMap: function(){
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
//guarda a posicao currente do utilizador
this.pos = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: this.map,
position: this.pos
});
console.log("a minha posicao eh: " + this.pos);
this.map.setCenter(this.pos);
});
}
var mapOptions = {
zoom: 8,
//center: new google.maps.LatLng(-34.397, 150.644)
};
this.map = new google.maps.Map(this.$el.find('#map_canvas')[0],mapOptions);
},
render: function(){
this.$el.html(this.template());
this.initMap();
return this;
}
});
main.js:
var ev = new Application();
ev.Router = Backbone.Router.extend({
routes: {
"": "home"
},
initialize: function() {
// Caching the Welcome View
this.homeView = new ev.views.Home();
},
home: function() {
$('#home').html(this.homeView.el);
}
});
$(document).on('ready', function() {
// Load HTML templates for the app
ev.templateLoader.load(['shell', 'home'], function() {
ev.shell = new ev.views.Shell({el: "#shell"});
ev.router = new ev.Router();
Backbone.history.start();
});
});
我沒有落後initMap功能的邏輯。爲什麼你在最後初始化地圖?它看起來像當你調用initMap函數時,條件成立,因爲導航器將在大多數現代Web瀏覽器中具有凝膠位置;所以它直接進入條件並嘗試設置中心(this.map.setCenter),但它沒有找到「this.map」。 – Sadik 2014-12-09 11:35:18
我創建了該函數來初始化地圖,如果我刪除'if(navigator)'裏面的代碼,則顯示我定義的具有經度和緯度的地圖。 – seal 2014-12-09 11:42:25