user1623347
user1623347

Reputation: 15

Google Maps API v3 - Hidden Div - Map not centered in div

I've looked at several questions that are similar, but I'm still not finding a resolution.

I have this page: http://www.citizensmemorial.com/Test2014/locations/cmh-infectious-disease-and-internal-medicine-clinic/index.html

I'm using this code:

<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBs_4MZDYZTCtkoB-Hbo4qQyWy-qHQuEdA"></script>
<script>
var mapExists = document.getElementById('map-canvas'); if(mapExists) 
var map;
function initialize() {
var myLatLng = new google.maps.LatLng (37.625387, -93.424350)
  var mapOptions = {    
    zoom: 12,
    center: myLatLng
  };   
 map = new google.maps.Map(document.getElementById('map-canvas'),
      mapOptions);
       var marker = new google.maps.Marker({
      position: myLatLng,
      map: map,
      title: 'CMH Infectious Disease & Internal Medicine Clinic'
});
}
google.maps.event.addDomListener(window, 'load', initialize);
    </script>

Here is the applicable css:

html, body, #map-canvas {
    width:100%;
    height:100%
}
#map_canvas {
position: relative;
}
.map-holder {
width:500px;
    height:270px;
    padding: 0px;
    display:table; 
    margin-top:3px; 
    float:right;
}

I'm assuming that it is something related to the css that is keeping the map from centering, as I've tested the map code by itself at this url and it is working: http://www.citizensmemorial.com/Temp/mapTest.html

Upvotes: 0

Views: 1296

Answers (2)

Eko Junaidi Salam
Eko Junaidi Salam

Reputation: 1681

I've checked your code. Please check this css that apply to the page you've tested. If your problem's about the CSS.

You can use firebug to test the css.

<div id='map-canvas' style="position: relative; background-color: rgb(229, 227, 223); overflow: hidden;"></div>

and your code it self, it run as normal. and if you want to centered the map based on a marker or infowindow. you can use map.setCenter(map); as for infowindow you can use position in your opts. for detail information and references please read this.

Upvotes: 0

TResponse
TResponse

Reputation: 4125

Looks to be you are initializing the map before the map-canvas div is visible. You need to trigger a resize otherwise the map won't know its correct size.

After initializing your map call a map resize

google.maps.event.trigger(map, "resize");

Then set map centre to your marker.

map.setCenter(markerlatlng);

Upvotes: 1

Related Questions