I have a set of points I want to plot on an embedded Google Map (API v3). I\'d like the bounds to accommodate all points unless the zoom level is too low (i.e., zoomed out
I solved a similar problem in one of my apps. I was a little confused by your description of the problem, but I think you have the same goal I had...
In my app I wanted to plot a one or more markers and ensure the map was showing them all. The problem was, if I relied solely on the fitBounds method, then the zoom-level would be maxed out when there was a single point - that was no good.
The solution was to use fitBounds when there was many points, and setCenter+setZoom when there was only one point.
if (pointCount > 1) {
map.fitBounds(mapBounds);
}
else if (pointCount == 1) {
map.setCenter(mapBounds.getCenter());
map.setZoom(14);
}
I have come to this page multiple times to get the answer, and while all the existing answers were super helpful, they did not solve my problem exactly.
google.maps.event.addListenerOnce(googleMap, 'zoom_changed', function() {
var oldZoom = googleMap.getZoom();
googleMap.setZoom(oldZoom - 1); //Or whatever
});
Basically I found that the 'zoom_changed' event prevented the UI of the map from "skipping" which happened when i waited for the 'idle' event.
Hope this helps somebody!
I had the same issue and I was able to solve it using the following code. This listener (google.maps.addListenerOnce()
) event will only get fired once, right after map.fitBounds()
is executed. So, there is no need to
idle
.It sets the appropriate zoom level initially and allows the user to zoom in and out past the initial zoom level because the event listener has expired. For example, if only google.maps.addListener()
was called, then the user would never be able to zoom-in past the stated zoom level (in the case, 4). Since we implemented google.maps.addListenerOnce()
, the user will be able to zoom to any level he/she chooses.
map.fitBounds(bounds);
var zoom_level_for_one_marker = 4;
google.maps.event.addListenerOnce(map, 'bounds_changed', function(event){
if (this.getZoom() >= zoom_level_for_one_marker){
this.setZoom(zoom_level_for_one_marker)
}
});
I don't like to suggest it, but if you must try - first call
gmap.fitBounds(bounds);
Then create a new Thread/AsyncTask, have it sleep for 20-50ms or so and then call
gmap.setZoom( Math.max(6, gmap.getZoom()) );
from the UI thread (use a handler or the onPostExecute
method for AsyncTask).
I don't know if it works, just a suggestion. Other than that you'd have to somehow calculate the zoom level from your points yourself, check if it's too low, correct it and then just call gmap.setZoom(correctedZoom)
Edit: See Matt Diamond's comment below.
Got it! Try this:
map.fitBounds(bounds);
var listener = google.maps.event.addListener(map, "idle", function() {
if (map.getZoom() > 16) map.setZoom(16);
google.maps.event.removeListener(listener);
});
Modify to your needs.