Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the bounds of a polyline in Google Maps API v3

Is there any easy ways to find the bounding box of a polyline using Google Maps API v3? I'm working on a project where I need to update the bounds as data is added and removed from the map. This is pretty easy by just doing bd.extend(point) where bd is the bound object and point is a LatLng object. The problem is when I start removing data I would like it to change the bounds and zoom back in. Are there any built in functions that can do this or will I need to write something for myself?

like image 216
Ian Burris Avatar asked Jul 19 '10 20:07

Ian Burris


2 Answers

Expanding on oenpelli's solution, this is the extended getBounds() method that I am using to recreate the functionality from V2 API. This is working perfectly in my project.

google.maps.Polyline.prototype.getBounds = function() {
    var bounds = new google.maps.LatLngBounds();
    this.getPath().forEach(function(item, index) {
        bounds.extend(new google.maps.LatLng(item.lat(), item.lng()));
    });
    return bounds;
};

Just remember that this needs to be added AFTER the API javascript is loaded, so in your init method.

like image 83
Jamie Carl Avatar answered Sep 20 '22 08:09

Jamie Carl


The v2 API had the GPolyline.getBounds() method to do exactly this. However it appears that there is no equivalent method in the v3 API.

You may want to handle this by overriding the changed property of your Polyline MVCObject in order to be notified when the object changes state. Then you can calculate the bounding box using the LatLngBounds.extend() method that you suggested.

I think Google intentionally omitted such methods from the v3 API in an attempt to keep the API lightweight. A similar omission discussed a couple of days ago on Stack Overflow was the GMap2.clearOverlays() method.

like image 26
Daniel Vassallo Avatar answered Sep 18 '22 08:09

Daniel Vassallo