How to center / align Google Maps in a variable width div

I have Google Maps loaded in a div, at 100% page width (via API). The overlay is located in the center, and the map should be located as shown. The problem is that the map is now aligned to the left.

I could move the center using LatLng corresponding to the page width, but this seems like a lot of work for a simple task. I was looking through the API link but could not find a solution.

Is there any way in the Maps API (v3) to place / align the map in / in the center?

Edit:

When resizing the browser window in this example:

http://econym.org.uk/gmap/example_fullscreen1.htm

The map is aligned to the edge of the window.

I want the center of the map to stay in the center of the window when resizing.

Thus, the map will move 100 pixels to the right if the window is 200 pixels wider.

+6
source share
4 answers

having two div , one inside the other, you can center the inner, even using percentages.
and attach an event handler to re-center the map in each resize event.

HTML

 <div id="outerdiv"> <div id="map_go" /> </div> 

Js

 $(window).on('resize', function() { var currCenter = map.getCenter(); google.maps.event.trigger(map, 'resize'); map.setCenter(currCenter); }) 

CSS

 #outerdiv {width: 90%; height: 90%; position:fixed; text-align:center} #map_go {width: 70%; height: 100%; margin:0px auto; display:inline-block} 

see here: http://jsfiddle.net/RASG/eXCFw/

verified using firefox 15

+7
source

I tried this and it worked fine for me

 #map-canvas { height: 70%; width :50%; margin-left:auto; margin-right:auto;} 
+4
source

This should help: http://econym.org.uk/gmap/basic19.htm

It describes problems with div sizes and maps (which should know the size of the map displayed). This is from Mike Williamsโ€™s Google Maps API v2 tutorial, but the concept applies to v3 too.

+1
source

I do not understand why you will need 2 DIV for this.

One div is enough:

 $(window).resize(function() { var currCenter = map.getCenter(); google.maps.event.trigger(map, 'resize'); map.setCenter(currCenter); }); 

Please check http://jsfiddle.net/RGUnd/2/

0
source

All Articles