开发者

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 ad开发者_StackOverflowded 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?


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜