Getting the bounds of a polyline in Google Maps API v3

房东的猫 提交于 2020-01-02 03:31:08

问题


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?


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/3284808/getting-the-bounds-of-a-polyline-in-google-maps-api-v3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!