Google maps API V3 method fitBounds()
I have this code that renders a map.
function initialize() {
var myOptions = {
center: new google.maps.LatLng(45.4555729, 9.169236),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP,
panControl: true,
mapTypeControl: false,
panControlOptions: {
position: google.maps.ControlPosition.RIGHT_CENTER
},
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE,
position: google.maps.ControlPosition.RIGHT_CENTER
},
scaleControl: false,
streetViewControl: false,
streetViewControlOptions: {
position: google.maps.ControlPosition.RIGHT_CENTER
}
};
var map = new google.maps.Map(document.getElementById("mapCanvas"),
myOptions);
var Item_1 = new google.maps.LatLng(45.5983128 ,8.9172776);
var myPlace = new google.maps.LatLng(45.4555729, 9.169236);
var marker = new google.maps.Marker({
position: Item_1,
map: map});
var marker = new google.maps.Marker({
position: myPlace,
map: map});
var bounds = new google.maps.LatLngBounds(myPlace, Item_1);
map.fitBounds(bounds);
}
Even if the two points are separated from 25 km I get this result:
While I would like to render a higher level zoom.
Like this
I use the method fitBounds()
var bounds = new google.maps.LatLngBounds(myPlace, Item_1);
map.fitBounds(bounds);
Thanks for your support
This happens because LatLngBounds()
does not take two arbitrary points as parameters, but SW and NE points
use the .extend()
method on an empty bounds object
var bounds = new google.maps.LatLngBounds();
bounds.extend(myPlace);
bounds.extend(Item_1);
map.fitBounds(bounds);
Demo at http://jsfiddle.net/gaby/22qte/
LatLngBounds
must be defined with points in (south-west, north-east) order. Your points are not in that order.
The general fix, especially if you don't know the points will definitely be in that order, is to extend an empty bounds:
var bounds = new google.maps.LatLngBounds();
bounds.extend(myPlace);
bounds.extend(Item_1);
map.fitBounds(bounds);
The API will sort out the bounds.
I have the same problem that you describe although I'm building up my LatLngBounds as proposed by above. The problem is that things are async and calling map.fitBounds()
at the wrong time may leave you with a result like in the Q.
The best way I found is to place the call in an idle handler like this:
google.maps.event.addListenerOnce(map, 'idle', function() {
map.fitBounds(markerBounds);
});
var map = new google.maps.Map(document.getElementById("map"),{
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < locations.length; i++){
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
bounds.extend(marker.position);
}
map.fitBounds(bounds);