Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Maps v3 + Backbone + Marionette: Map fails to render the second time

I'm trying to display a map by creating a view and inserting it into DOM, and it works fine the first time, but fails on subsequent invocations of the view, displaying a gray empty area.

Here is the JSFiddle of the problem: http://jsfiddle.net/dyuvH/14/

Everything works fine when you click on the 'Click to load map' link, but will fail if you do it again.

I'm loading a map into a view using the following:

onRender: function() {
    var mapOptions = {
        center: new google.maps.LatLng(-34.397, 150.644),
        zoom: 8,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    var mapView = new App.MapView();
    var map = new google.maps.Map(mapView.el, mapOptions);
    mapView.render();
    this.ui.mapContainer.html(mapView.el);
}

Again, everything works perfectly the first time and fails the second. I'm thinking the view is holding on to some aspect of the map or vice-versa. I do create new instances of the map and the view using the "new" keyboard in both cases, so I'm not sure what's messed up.

Any help is appreciated.

like image 215
Nightwolf Avatar asked Mar 25 '23 09:03

Nightwolf


2 Answers

The call to mapView.render() is not necessary, and can be removed or commented out. That will at least get the map to render upon subsequent clicks.

You will also need to compensate for Issue 1448 in the GMaps API v3. Something along this code should work to solve the off-centered map on subsequent renderings:

    google.maps.event.addListener(map, "idle", function(){
        map.setCenter(mapOptions.center);
        google.maps.event.trigger(map, 'resize');
    }); 

For reference, the updated jsFiddle with the above suggestions.

like image 198
Laurence A. Lee Avatar answered Apr 25 '23 03:04

Laurence A. Lee


I had the same problem and after reading #19 of Issue1448 I decided to use onShow instead of onRender and then it worked like a charm. This way I didn't need to trigger any map resize event or trying to work out the center of the map.

like image 38
mrydengren Avatar answered Apr 25 '23 03:04

mrydengren