Google Maps API:计算折线的中心/缩放 [英] Google Maps API: Calculate Center/Zoom of Polyline

查看:113
本文介绍了Google Maps API:计算折线的中心/缩放的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从用户数据动态生成的覆盖图,所以我需要知道如何找到覆盖图的中心。

I have an overlay that is dynamically generated from user data, so I need to know how to find the center of that overlay.

目前,我只是使用覆盖图中的第一个坐标,但实际上并不代表覆盖图的中心。因此,当我加载地图时,它并没有以覆盖为中心。

Currently, I am just using the first coordinates from the overlay, but that really does not represent the center of the overlay. Therefore when I load the map, it is not centered on the overlay.

有没有人有一个好的方法来将地图定位在覆盖图上,通过计算中心而不是硬编码吗?

Does anyone have a good method for centering the map on the overlay, by calculating the center, not hard coding it?

var latlng = new google.maps.LatLng(38.269239, -122.276010);
    var myOptions = {
        zoom: 15,//Calculate this somehow?
        center: latlng,// Calculate value from array of coordinates?
        mapTypeId: google.maps.MapTypeId.HYBRID
    };


推荐答案

如果你有一个坐标列表,你可以循环并将它们添加到 LatLngBounds 对象。这里是V3 API的一个例子,但是V2中的概念是类似的:

If you have a list of coordinates, you can loop over them and add them to a LatLngBounds object. Here is a example for the V3 API, but the concept in V2 is similar:

var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < coordinates.length; i++) {
  bounds.extend(coordinates[i]);
}

之后,您可以通过以下方式获取该中心:

After that, you can get the center with:

bounds.getCenter();

或者,您可以调用 map.fitBounds()直接,它将围绕边界中心的地图居中,并调整缩放,以便整个边界将完全适合视图端口。

Or alternatively, you can call map.fitBounds() directly, which will center the map around the center of the bounds and adjust the zoom, so that the whole bounds will fit exactly into the view port.

map.fitBounds(bounds);

这篇关于Google Maps API:计算折线的中心/缩放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆