Google Maps not centering because div is display:none on page load

Viewed 26256

I have a web-page that contains a hidden <div> using display: none; and I have a button on the page, that when clicked will change the visibility of the <div>, and overlay it on top of everything else (because it has a z-index set).

Within this <div>, I have a Google Map embedded using an iFrame with the Google Map pin dropped on the location I am trying to show to my users.

The problem

Because the Google Maps iFrame is loading on the page load and while the <div> is hidden, it means that when the <div> is shown the Google Map is not aligned properly (the pin and central location are now in the top left hand corner)

The solution I am looking for

I know that some people are probably going to tell me ways in which I "should" recode my entire page. What I am actually looking for is some sort of onClick function I can set that will reload the iFrame so that the map is properly centered.

Things to know

This iframe has a Google Maps page as its src. i.e. a URL rather than a link to a file in my site.

Any help would be greatly appreciated! A lot of code I have looked at searching the net seems to work at refreshing a specific file that is referenced rather than an external URL.

Would it work if I embedded the map in another HTML file, and then placed that HTML file as the frame source?

15 Answers

I had the same problem, my solution was to set both the div & the iframe to 0px height and then have it changed to the desired height when toggled.

<script language="javascript"> 
function toggle() {
    var ele = document.getElementById("toggleText");
    var ifr = document.getElementById("iframe");
    var text = document.getElementById("displayText");
    if(ele.style.visibility == "visible") {
            ele.style.visibility = "hidden";
        ele.style.height = "0px";
        ifr.style.height = "0px";
        text.innerHTML = "<img src='#' border='0' width='180' height='65'>";
    }
    else {
        ele.style.visibility = "visible";
        ele.style.height = "420px";
        ifr.style.height = "420px";
        text.innerHTML = "<img src='#' border='0' width='180' height='65'>";
    }
} 
</script>

<div id="mb">
<a id="displayText" href="javascript:toggle();"><img src="#" border="0" width='180' height='65'></a>
</div>


<div id="toggleText"  style="visibility: hidden; height: 0px;">
<p><iframe id="iframe" style="height: 0px;" src=#" width="650">
</iframe></div>
Related