Getting the bounds of a polyline in Google Maps API v3
Asked Answered
G

3

7

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?

Guereza answered 19/7, 2010 at 20:31 Comment(0)
D
4

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.

Divulsion answered 19/7, 2010 at 20:51 Comment(0)
P
16

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.

Philately answered 8/4, 2016 at 0:57 Comment(0)
D
4

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.

Divulsion answered 19/7, 2010 at 20:51 Comment(0)
O
2

You can also extend the Polyline class to add your own getBounds method. Refer to google maps api v3: add point on polyline beetwen two existing points on click polyline event for how to do this.

Oleviaolfaction answered 13/1, 2011 at 0:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.