google map V3 div position fixed change relative

user1253414 picture user1253414 · Jul 3, 2012 · Viewed 7.9k times · Source

First, sorry for my english because is not good.

I have a problem with a google map. I'm trying to get a map in a div, and I want that this div with position:fixed.

My problem is after to draw the map because change the position of the div. In the beginning is fixed and after to drawn is relative and change the position of the div.

Here is my code, HTML

<div class="verMapa"> SEE MAP </div>        
<br><br><br>        
<div>
  <div id="mask" style="display:none; background-color:#000000; position:absolute; right:0; top:0; z-index:9000;"></div>

  <div id="capaMapa" style= "display:none; background-color:white; position:fixed; top:50%; left:50%; width:600px; height:400px; margin-top:-200px; margin-left:-300px;z-index:9900;">
  </div>
</div>

CODE Javascript

var map = null;

$(document).ready(function(){

    //Evento click en Mask que cierra el mapa.
    $("#mask").click(function(){    
        $('#mask').hide();
        $('#capaMapa').hide();
        $('#capaMapa').html("");
    });


    //Evento click en ver mapa
    $(".verMapa").click(function(){ 

        //Get the screen height and width
        var maskHeight = $(document).height();
        var maskWidth = $(window).width();

        //Set height and width to mask to fill up the whole screen
        $('#mask').css({'width':maskWidth, 'height':maskHeight});

        //transition effect
        $('#mask').fadeIn(1000);
        $('#mask').fadeTo("slow", 0.5);

        //transition effect
        $('#capaMapa').fadeIn(2000);

        initialize(40, -1);

    });

});


function initialize(latitud, longitud) {              

    myOptions = {
        zoom: 14,
        center: new google.maps.LatLng(latitud, longitud),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }

    //inicializamos el mapa.
    map = new google.maps.Map(document.getElementById("capaMapa"), myOptions);  

}

After click en "see map" I can see the map correctly but in error position if I see code in firebug. style in div "capaMapa" has changed and now position:relative and this div is drawn in error position.

I have seen that this change after initialize map, "map = new google.maps.Map(document.getElementById("capaMapa"), myOptions);" because if I comment this line, to draw div in correct position.

Any suggest?

Answer

The DOM element containing the map (#capaMapa in your example) will always have position: relative;. Try enclosing it in another element that you can style as intended:

<div id="capaMapa"><div id="map-canvas"></div></div>

Your CSS:

#capaMapa {
    display:none;
    background-color:white;
    position:fixed;
    top:50%;
    left:50%;
    width:600px;
    height:400px;
    margin-top:-200px;
    margin-left:-300px;
    z-index:9900;
}

#map-canvas {
    position: relative; /* Will be set by the Maps API anyway */
    width: 100%;
    height: 100%;
}