I have an app where users set a home location and page through results. The home and results are displayed on the map. As the results displayed on the map change, the map adjusts to include all markers:
bounds = new google.maps.LatLngBounds();
//
// add markers to bounds
//
for (i = 0, l = markers.length; i < l; i ++) {
bounds.extend(markers[i].getPosition());
}
this.map.fitBounds(bounds);
However, I also need to keep the map centered on the 'home' location. The home marker is included in the bounds, but it is not necessarily the center.
I know that this.setCenter(home)
will shift the map's center, but that will not necessarily ensure all the markers are still visible.
I've thought of finding the point the greatest distance from home
and using that radius as a way of setting the bounds around home
instead of just including home
. But if it isn't necessary to fit the whole circle into the square viewport, I'd prefer that.
Has anyone solved this?
Editing to answer my own question -
the linked question is a duplicate, but does not actually answer my question. LatLngBounds.contains() requires a LatLng and does not accept a bounds object: LatLngBounds. Led me in the right direction though.
map.fitBounds(bounds);
map.setCenter(center);
newbounds = map.getBounds();
for (i = 0; i < l; i ++) {
if (!newbounds.contains(markers[i].getPosition())) {
contained = false;
}
}
if (!contained) map.setZoom(map.getZoom() - 1);