Как я могу получить наименьшее значение LatLngBounds, которое все еще содержит набор координат широты / долготы в API Карт Google JS? - PullRequest
5 голосов
/ 30 июля 2010

Мне нужно нанести на карту набор координат в ответ на выбор пользователя, и когда это произойдет, я бы хотел повернуть карту, чтобы сфокусироваться на этом наборе точек. Как найти наименьшую ограничивающую рамку (LatLngBounds), которая содержит все координаты?

1 Ответ

12 голосов
/ 31 июля 2010

В дополнение к сообщению Stack Overflow, на которое @Crescent Fresh указал выше (который использует API v2), вы должны использовать метод LatLngBounds.extend().

Вот полный пример использования v3 API :

<!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 America
     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>

Скриншот:

Google Maps LatLngBounds.extend() Demo

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...