javascriptgoogle-mapsgoogle-maps-api-3fitbounds

Google Maps JS API - How to use fitBounds for responsive map?


I'm trying to show a certain area in a map in a responsive website. I want it to display the same area, when loaded, whatever is the window size, by zooming in and out. After some research I understood I need to use the fitBounds function of the Google Maps JS API, but can't get it to work. Here's my code so far:

<div id="map"></div><!--css rules to make it a 16/9 responsive box-->
<script src="https://maps.googleapis.com/maps/api/js?key=mykey" type="text/javascript"></script>
<script type="text/javascript">
function initialize() {
    var mapOptions = {
        center: new google.maps.LatLng(x, y), //any coordinates I put here don't matter, as I need the map to adjust using bounds, right?
        zoom: 11
    };
    var bounds = google.maps.LatLngBounds(
        new google.maps.LatLng(x, y), //SW coordinates here
        new google.maps.LatLng(x, y) //NE coordinates here
    );
    var map = new google.maps.Map(document.getElementById("map"), mapOptions);
    map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.addDomListener(window, "resize", function() {
    var bounds = map.getBounds();
    google.maps.event.trigger(map, "resize");
    map.fitBounds(bounds);
});
</script>

It seems the map is just showing the center position in the options, and ignoring the fitBounds call. What am I missing/doing wrong?


Solution

  • You are currently retrieving the bounds of the map before its had a chance to resize

    You need to add an extra handler for the map resize event and then move your fitBounds code into that. Still keep your trigger of the map resize in the window resize handler.

    Edit

    You need to move your map variable outside of your initialize function so its globally accessible to your map listeners