Reputation: 266
I don't know why this doesn't seem to work. I want the map to have the bounds set according to a circle's bounds but it doesn't zoom in enough and there is way too much padding, so I try an increase in zoom after fitBounds and it does nothing.
???
LatLngD and LatLngO are global and are set elsewhere.
function initializeMap() {
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 10,
center: LatLngO,
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoomControl: false
});
setRadius();
}
function setRadius() {
var distance = google.maps.geometry.spherical.computeDistanceBetween(LatLngO, LatLngD);
circle = new google.maps.Circle({
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: map,
center: LatLngO,
radius: distance,
});
map.fitBounds(circle.getBounds());
map.setZoom(map.getZoom() + 1);
}
Upvotes: 0
Views: 571
Reputation: 161384
The Google Maps Javascript API v3 is event based. You need to wait until the new zoom level takes effect before incrementing it by one.
map.fitBounds(circle.getBounds());
google.maps.event.addListenerOnce(map, 'bounds_changed', function() {
map.setZoom(map.getZoom() + 1);
});
(The addListenerOnce
performs the action once, then removes the event listener)
code snippet:
var LatLngO = new google.maps.LatLng(42, -72);
var LatLngD = new google.maps.LatLng(42.5, -72.7);
function initializeMap() {
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 10,
center: LatLngO,
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoomControl: false
});
setRadius();
}
function setRadius() {
var distance = google.maps.geometry.spherical.computeDistanceBetween(LatLngO, LatLngD);
circle = new google.maps.Circle({
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: map,
center: LatLngO,
radius: distance,
});
map.fitBounds(circle.getBounds());
google.maps.event.addListenerOnce(map, 'bounds_changed', function() {
map.setZoom(map.getZoom() + 1);
});
}
google.maps.event.addDomListener(window, "load", initializeMap);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map_canvas"></div>
Upvotes: 2
Reputation: 96959
This is usually done using the idle
event which is called after the map has initialized and set its bounds properly:
var listener = google.maps.event.addListener(map, "idle", function() {
map.setZoom(map.getZoom() - 1);
google.maps.event.removeListener(listener);
});
Upvotes: 1