How to get LatLngBounds of feature polygon geometry in google maps v3?

前端 未结 3 1266
耶瑟儿~
耶瑟儿~ 2020-12-18 19:24

I have a lot of polygonal features loaded with loadGeoJson and I\'d like to get the latLngBounds of each. Do I need to write a function that iterates through every lat long

相关标签:
3条回答
  • 2020-12-18 20:13

    Here's another solution for v3 Polygon :

    var bounds = new google.maps.LatLngBounds();
    
    map.data.forEach(function(feature){
      if(feature.getGeometry().getType() === 'Polygon'){
        feature.getGeometry().forEachLatLng(function(latlng){
          bounds.extend(latlng);
        });
      }
    });
    
    0 讨论(0)
  • 2020-12-18 20:17

    In Google Maps JavaScript API v2, Polygon had a getBounds() method, but that doesn’t exist for v3 Polygon. Here’s the solution:

    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 讨论(0)
  • 2020-12-18 20:27

    The Polygon-features doesn't have a property that exposes the bounds, you have to calculate it on your own.

    Example:

       //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 讨论(0)
提交回复
热议问题