Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
459 views
in Technique[技术] by (71.8m points)

javascript - How to set the Google Map zoom level to show all the markers?

How do I set the zoom level to show all the markers on Google Maps?

In my Google Map there are different markers in different positions. I want to set google map zoom level based on the range of markers (that means in the view of google map, i want to see all markers)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There you go:

<!DOCTYPE html>
<html> 
<head> 
   <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
   <title>Google Maps getBoundsZoomLevel Demo</title> 
   <script src="http://maps.google.com/maps?file=api&amp;v=2&amp;sensor=false" 
           type="text/javascript"></script> 
</head> 
<body onunload="GUnload()"> 

   <div id="map" style="width: 400px; height: 300px"></div> 

   <script type="text/javascript"> 

   if (GBrowserIsCompatible()) {
      var map = new GMap2(document.getElementById("map"));
      var markerBounds = new GLatLngBounds();

      for (var i = 0; i < 10; i++) {
         var randomPoint = new GLatLng( 39.00 + (Math.random() - 0.5) * 20, 
                                       -77.00 + (Math.random() - 0.5) * 20);

         map.addOverlay(new GMarker(randomPoint));
         markerBounds.extend(randomPoint);
      }

      map.setCenter(markerBounds.getCenter(), 
                    map.getBoundsZoomLevel(markerBounds));
   }
   </script> 
</body> 
</html>

We are creating 10 random points in the above example and then passing each point to GLatLngBounds.extend(). Finally we get the correct zoom level with GMap2.getBoundsZoomLevel().

Google Maps getBoundsZoomLevel Demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...