Tuesday, May 28, 2024
 Popular · Latest · Hot · Upcoming
69
rated 0 times [  71] [ 2]  / answers: 1 / hits: 45208  / 14 Years ago, thu, august 19, 2010, 12:00:00

I think the title is enough, I don't even see how to do this for the V2 and V1 API :/



Thanks :)


More From » google-maps

 Answers
80

As the other answers suggested, the fitBounds() method should do the trick.



Consider the following example, which will generate 10 random points on the North East USA, and applies the fitBounds() method:



<!DOCTYPE html>
<html>
<head>
<meta http-equiv=content-type content=text/html; charset=UTF-8/>
<title>Google Maps LatLngBounds.extend() Demo</title>
<script src=http://maps.google.com/maps/api/js?sensor=false
type=text/javascript></script>
</head>
<body>
<div id=map style=width: 400px; height: 300px;></div>

<script type=text/javascript>

var map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.TERRAIN
});

var markerBounds = new google.maps.LatLngBounds();

var randomPoint, i;

for (i = 0; i < 10; i++) {
// Generate 10 random points within North East USA
randomPoint = new google.maps.LatLng( 39.00 + (Math.random() - 0.5) * 20,
-77.00 + (Math.random() - 0.5) * 20);

// Draw a marker for each random point
new google.maps.Marker({
position: randomPoint,
map: map
});

// Extend markerBounds with each random point.
markerBounds.extend(randomPoint);
}

// At the end markerBounds will be the smallest bounding box to contain
// our 10 random points

// Finally we can call the Map.fitBounds() method to set the map to fit
// our markerBounds
map.fitBounds(markerBounds);

</script>
</body>
</html>


Refreshing this example many times, no marker ever goes outside the viewport:



fitBounds


[#95876] Monday, August 16, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mckaylab

Total Points: 311
Total Questions: 120
Total Answers: 93

Location: Montenegro
Member since Thu, Jun 16, 2022
2 Years ago
;