Skip to content

Instantly share code, notes, and snippets.

@markthethomas
Created June 16, 2014 17:26
Show Gist options
  • Save markthethomas/5da15a050f560cc58d4f to your computer and use it in GitHub Desktop.
Save markthethomas/5da15a050f560cc58d4f to your computer and use it in GitHub Desktop.
Re-center google map on window resize
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html {
height: 100%
}
body {
height: 100%;
margin: 0;
padding: 0
}
#map-canvas {
height: 100%
}
@media screen and (min-width: 1200px) {
.maps {
width: 600px;
}
}
@media screen and (max-width: 320px) {
.maps {
width: 160px;
}
}
</style>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY_GOES_HERE">
</script>
<script src="map.js"></script>
</head>
<body>
<div id="map-canvas" />
</body>
</html>
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(-34.397, 150.644),
zoom: 8
};
var map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
// create a variable to hold center
var center;
// calculate the center with getCenter
function calculateCenter() {
center = map.getCenter();
}
// Add an event listener that calculates center on idle
google.maps.event.addDomListener(map, 'idle', function() {
calculateCenter();
});
// Add an event listener that calculates center on resize
google.maps.event.addDomListener(window, 'resize', function() {
map.setCenter(center);
});
}
// boilerplate initialization
google.maps.event.addDomListener(window, 'load', initialize);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment