I'm learning backbone and I started to build an application that uses google maps. My problem is that when I try to render google maps in my view nothing happens, only appears the div
that contains id="map_canvas"
in gray, like this:
and in my console log I have this error Uncaught TypeError: Cannot read property 'setCenter' of undefined
Code of my view:
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();
});
});
try this I haven't tested:
initMap: function(){
this.map = new google.maps.Map(this.$el.find('#map_canvas')[0],mapOptions);
var that = this;
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
//guarda a posicao currente do utilizador
that.pos = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: that.map,
position: that.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)
};
},