It is easy enough to center a marker that is outside the current bounds of a google map:
if (!map.getBounds().contains(marker.getPosition())) {
myMap.panTo(pos)
}
What I want to do is imitate the infoWindow autopan for a marker, where if the marker is not in bounds the map only pans far enough to get it in bounds. Is there an easier way to do this other than manually calculating the distance from the edges of the bounds and setting a "false" center that only moves it the necessary distance? I tried fitBounds and it zoomed in and still centered the marker...
Here is a JSBin with a 'hack' solution that doesn't involve any lat/lng or bounds calculations on your part. Make sure to replace YOUR_API_KEY
in the HTML with your Google Maps API key. Press the "Place Random Marker" button at the bottom of the map to see it in action.
This solution uses the auto pan functionality of InfoWindow objects to pan the map far enough so that the marker is just within bounds.
The part of the code that handles the panning is in the map.panToMarker
method. Here is its body:
var infoWindow = new google.maps.InfoWindow();
infoWindow.open(this.map, this.marker);
google.maps.event.addListenerOnce(this.map, 'center_changed', function() {
infoWindow.close();
});
I create a new InfoWindow and call open
on it, passing the map and marker as arguments. This causes the map to pan to the marker. Then, I create a MapsEventListener that listens for the 'center_changed' event on the map. Once it detects that the map's center has changed, the info window is closed and the listener is removed.