Google Maps JavaScript API v3: method Polyline.getBounds


In Google Maps JavaScript API v2, Polyline had a getBounds() method, but that doesn’t exist for v3 Polyline. I wrote some methods below:

Method 1:

if (!google.maps.Polyline.prototype.getBounds)
google.maps.Polyline.prototype.getBounds = function() {

  var path = this.getPath();
  
  var slat, blat = path.getAt(0).lat();
  var slng, blng = path.getAt(0).lng();

  for (var i = 1; i < path.getLength(); i++) {
    var e = path.getAt(i);
    slat = ((slat < e.lat())?slat:e.lat());
    blat = ((blat > e.lat())?blat:e.lat());
    slng = ((slng < e.lng())?slng:e.lng());
    blng = ((blng > e.lng())?blng:e.lng());
  }      

  return new google.maps.LatLngBounds(new google.maps.LatLng(slat, slng), new google.maps.LatLng(blat, blng));
  
}

Method 2:

if (!google.maps.Polyline.prototype.getBounds) {
   google.maps.Polyline.prototype.getBounds = function(latLng) {
      var bounds = new google.maps.LatLngBounds();
      var path = this.getPath();
      for (var i = 0; i < path.getLength(); i++) {
         bounds.extend(path.getAt(i));
      }
      return bounds;
   }
}

Method 3:

if (!google.maps.Polyline.prototype.getBounds)
google.maps.Polyline.prototype.getBounds = function() {
  
  var bounds = new google.maps.LatLngBounds();
   
  this.getPath().forEach( function(latlng) { bounds.extend(latlng); } ); 
  
  return bounds; 
  
}

Method 3 is the shortest method.

Image copyright: Google Maps

Leave a Reply