I went through as many StackOverflow / google groups as I can imagine trying to understand this guy.
I am using BackboneJS to render a map with a starting location and ending location. On a new page / page refresh, I do not get this error, and the map and everything works fine, because I use the jQuery function $ (window) .load (.....); however, when I dynamically render my view, I get this error, I suppose, because the DOM has not loaded the DIV yet (crash with document.getElementById). I tried all kinds of methods other than $ (window) .load (), but I canβt get anything that works for both use cases (new page loading - loading BackboneJS). Trying to call a function immediately after the template does not work.
Any help would be appreciated.
Robert
View:
App.Views.MapShow = Backbone.View.extend({
initialize: function() {
_.bindAll(this, 'render');
var self = this;
$(window).load(function() {
self.renderMap();
});
},
render: function() {
this.renderTemplate();
},
renderTemplate: function() {
this.$el.html(JST['path/to/show/file']());
},
renderMap: function() {
var from = this.model.get('location_from');
var to = this.model.get('location_to');
var geocoder = new google.maps.Geocoder();
var map = new google.maps.Map(document.getElementById('mapCanvas'), {
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay.setMap(map);
var request = {
origin: from,
destination: to,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
});
HTML:
<div class="map" id="mapCanvas"></div>
source
share