1

I need an (independent) map on each jQuery Tab. Why does the map in the second tab have the same center as the first one?

Please see my JSFiddle http://jsfiddle.net/metaxos/KQpL6/2/

jQuery(document).ready(function () {
var map1;
var map2;

var myLatlng1 = new google.maps.LatLng(-34.397, 150.644);
var myOptions1 = {
    zoom: 8,
    center: myLatlng1,
    mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map1 = new google.maps.Map(document.getElementById("map_1"), myOptions1);

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

var map2 = new google.maps.Map(document.getElementById("map_2"), myOptions2);

var tabs = $( "#tabs" ).tabs({
    activate: function( event, ui ) {
        ui.newTab.index();

        if (ui.newTab.index() == '0') {
            google.maps.event.trigger(map1, 'resize');

        }
        if (ui.newTab.index() == '1') {
            google.maps.event.trigger(map2, 'resize');
        }
    }
    });
});
ChrisSwires
  • 2,713
  • 1
  • 15
  • 28
metaxos
  • 151
  • 1
  • 16

1 Answers1

0

I'm not entirely sure why but if you change:

var tabs = $( "#tabs" ).tabs({
activate: function( event, ui ) {
    ui.newTab.index();

    if (ui.newTab.index() == '0') {
        google.maps.event.trigger(map1, 'resize');

    }
    if (ui.newTab.index() == '1') {
        google.maps.event.trigger(map2, 'resize');
    }
    }
});

To:

var tabs = $( "#tabs" ).tabs({
activate: function( event, ui ) {
    ui.newTab.index();

    if (ui.newTab.index() == '0') {
        google.maps.event.trigger(map1, 'resize');

    }
    if (ui.newTab.index() == '1') {
        google.maps.event.trigger(map2, 'resize');
        map2.setCenter(myLatlng2);
    }
    }
});

Then everything works as expected. There must be some sort of interaction between the maps but I'm unsure why. I'll look into it. Updated fiddle.

ChrisSwires
  • 2,713
  • 1
  • 15
  • 28
  • 2
    This is the "map has zero size" (hidden element) problem. When you initialize map2, the div containing it is hidden and therefor reports a size of zero to the API, it centers the map in the upper left hand corner of the div. Triggering the resize event fixes the size, but doesn't recenter the map. – geocodezip Feb 21 '14 at 14:56
  • Yeah I'd just found some research and found this question: http://stackoverflow.com/questions/4064275/how-to-deal-with-google-map-inside-of-a-hidden-div-updated-picture which suggests the same. Is my answer a reasonable fix for this or is there a more appropriate solution? – ChrisSwires Feb 21 '14 at 15:03
  • Swires's code helped me out and works. The question got an "evolution" and there the trick seems not to help within a Iframe with Internet Explorer, see: http://stackoverflow.com/questions/21938179/one-google-maps-per-jquery-tab-in-iframe-map-positioning-defect-with-internet-ex – metaxos Feb 21 '14 at 15:20