Как получить LatLngBounds геометрии объекта многоугольника в google maps v3?

У меня много полигональных функций, загруженных loadGeoJson, и я бы хотел получить latLngBounds каждого из них. Нужно ли мне писать функцию, которая выполняет итерацию через каждую длинную пару лат в полигоне и выполняет расширение() на LatLngBounds для каждого, или есть лучший способ? (Если нет, я могу, вероятно, выяснить, как итерации через вершины многоугольника, но указатели на пример этого будут приветствоваться)

Ответы

Ответ 1

Элементы Polygon не имеют свойства, которое предоставляет границы, вы должны сами его вычислить.

Пример:

   //loadGeoJson  runs asnchronously, listen to the addfeature-event
   google.maps.event.addListener(map.data,'addfeature',function(e){

      //check for a polygon
      if(e.feature.getGeometry().getType()==='Polygon'){

          //initialize the bounds
          var bounds=new google.maps.LatLngBounds();

          //iterate over the paths
          e.feature.getGeometry().getArray().forEach(function(path){

             //iterate over the points in the path
             path.getArray().forEach(function(latLng){

               //extend the bounds
               bounds.extend(latLng);
             });

          });

          //now use the bounds
          e.feature.setProperty('bounds',bounds);

        }
  });

Демо: http://jsfiddle.net/doktormolle/qtDR6/

Ответ 2

В Google Maps JavaScript API v2 у Polygon был метод getBounds(), но это не существует для v3 Polygon. Это решение:

if (!google.maps.Polygon.prototype.getBounds) {
    google.maps.Polygon.prototype.getBounds = function () {
        var bounds = new google.maps.LatLngBounds();
        this.getPath().forEach(function (element, index) { bounds.extend(element); });
        return bounds;
    }
}

Ответ 3

Здесь другое решение для v3 многоугольника:

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

map.data.forEach(function(feature){
  if(feature.getGeometry().getType() === 'Polygon'){
    feature.getGeometry().forEachLatLng(function(latlng){
      bounds.extend(latlng);
    });
  }
});