2014-06-25 2 views
16

Ho un sacco di funzionalità poligonali caricate con loadGeoJson e mi piacerebbe ottenere il latLngBounds di ciascuno. Devo scrivere una funzione che itera su ogni lat long pair nel poligono e fa un extend() su un LatLngBounds per ognuno, o c'è un modo migliore? (In caso contrario, posso probabilmente capire come iterare attraverso i vertici del poligono ma i puntatori a un esempio di quello sarebbe il benvenuto)Come ottenere LatLngBounds della geometria poligonale della feature in google maps v3?

risposta

25

Le caratteristiche di Polygon non ha una proprietà che espone i limiti, devi calcolare da solo

Esempio:

//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); 

     } 
    }); 

Demo: http://jsfiddle.net/doktormolle/qtDR6/

+0

Questo non si applica ai MultiPolygon? –

+0

dove aggiungere più coordinate? O modificare le coordinate (Lat, Lng)? –

+1

@ manu29.d in v3, il controllo del tipo di geometria non è necessario. Basta chiamare e.feature.getGeometry(). ForEachLatLng (function (path) {bounds.extend (path);}) ha funzionato per me su un multipoligono. –

4

In Google Maps API JavaScript v2, Poligono avuto un getBounds() metodo, ma che non esiste per v3 Poligono. Ecco la soluzione:

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; 
    } 
} 
0

Ecco un'altra soluzione per v3 Poligono:

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

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