Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I've got a Google Maps loaded in a div that is 100% the width of the page (via API). The overlay is positioned in the center and the map should be positioned like this to. The problem is the map is now aligned to the left.

I could move the center with LatLng corresponding to the width of the page, but this seems like a lot of work for a simple task. I've been looking through the API-reference but couldn't find a solution.

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

Edit:

When you resize the browserwindow in this example:

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

The map is aligned to the topleft of the window.

What I want is the center of the map staying in the center of the window when resizing it.

So the map would move 100px to the right if the window got 200px wider.

like image 402
Tim Baas Avatar asked Oct 23 '12 15:10

Tim Baas


2 Answers

by having two div, one inside the other, you can center the inner one even using percentages.
and attach an event handler to re-center the map on 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 it working here: http://jsfiddle.net/RASG/eXCFw/

tested with firefox 15

like image 93
RASG Avatar answered Jan 02 '23 15:01

RASG


I tried this and it worked fine for me

#map-canvas { height: 70%; width :50%; margin-left:auto; margin-right:auto;}
like image 42
tuhame Avatar answered Jan 02 '23 16:01

tuhame