Подтвердить что ты не робот

Масштабируйте и центрируйте карту Google в соответствии с ее маркерами (JavaScript API V3)

Я думаю, что названия достаточно, я даже не вижу, как это сделать для V2 и V1 API:/

Спасибо:)

4b9b3361

Ответ 1

Как и другие ответы, метод fitBounds() должен сделать трюк.

Рассмотрим следующий пример, который будет генерировать 10 случайных точек на северо-востоке США и применяет метод fitBounds():

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

Обновляя этот пример много раз, маркер никогда не выходит за пределы области просмотра:

fitBounds demo

Ответ 2

Вот так:

map.fitBounds(bounds);
map.setCenter(bounds.getCenter());

bounds - это массив координат (маркеров). Каждый раз, когда вы помещаете маркер, делайте что-то вроде:

bounds.extend(currLatLng);

Ответ 3

Вычисление правильного масштабирования для отображения всех ваших маркеров не является тривиальным. Но есть функция для этого: GMap.fitBounds() - вы определяете привязку (например, самые крайние точки всех координат маркера), и она устанавливает карту соответствующим образом. См. fitbounds() в картах Google api V3 не соответствует ограничениям (ответ!) для хорошего примера.

Ответ 4

Центральное масштабирование зависит от одиночного маркера

var myCenter=new google.maps.LatLng(38.8106813,-89.9600172);
var map;
var marker;
var mapProp;
function initialize()
{
    mapProp = {
        center:myCenter,
        zoom:8,
        mapTypeId:google.maps.MapTypeId.ROADMAP
    };

    map=new google.maps.Map(document.getElementById("map"),mapProp);

    marker=new google.maps.Marker({
        position:myCenter,
        animation:google.maps.Animation.BOUNCE,
        title:"400 St. Louis Street Edwardsville, IL 62025"
    });

    marker.setMap(map);
    google.maps.event.addListener(map, "zoom_changed", function() {
        map.setCenter(myCenter);
    });
}

google.maps.event.addDomListener(window, 'load', initialize);