Search code examples
google-mapsgoogle-maps-api-3google-maps-markersfitbounds

Google Maps fitBounds not applying padding when only one point


I'm using Google Maps Javascript API.

Everytime the user search for some place, I show the marker of each place in my map and I use fitBounds to set the viewport to contain the given bounds.

As I have a panel above the map of 400px width on the right side, I apply a 400px of right padding in the fitBounds.

var bounds = new google.maps.LatLngBounds();
bounds.extend(new google.maps.LatLng(lat, lng)); //this line is executed inside a loop for every place
map.fitBounds(bounds, {right: 400});

When I have multiple points inside the bounds, the fitBounds works great applying the padding. But when I have only one point inside the bounds, the fitBounds does not apply the padding. Instead of that it works like panTo, only changing the center of the map.

Is that a bug in Google Maps API? Is there any workaround?


Solution

  • That seems to be a bug on the API, you can report it here.

    A workaround for the problem is using the panBy method when there is only one point after calling the fitBounds method, like in this fiddle.

    var bounds = new google.maps.LatLngBounds();
    bounds.extend(new google.maps.LatLng(lat, lng)); //this line is executed inside a loop for every place
    map.fitBounds(bounds, {right: 400});
    if (pointsCount == 1) { // initialize the var and use the loop to count
        map.panBy(200, 0); // has to be half of needed padding
    }