从中心点和缩放级别计算边界(Google Maps API v3)

6

我需要根据中心点和缩放级别计算地图的范围。

我想我可以暂时设置地图中心和缩放并调用map.getBounds(),但我不愿意这样做(我需要禁用/重新启用一些事件处理程序)。

有人知道如何在v3中实现此功能吗?

2个回答

11

这里使用了一点mootools,所以你需要编辑代码才能将其与其他库一起使用(应该很容易)。

/**
 * Calculates the bounds this map would display at a given zoom level.
 *
 * @member google.maps.Map
 * @method boundsAt
 * @param {Number}                 zoom         Zoom level to use for calculation.
 * @param {google.maps.LatLng}     [center]     May be set to specify a different center than the current map center.
 * @param {google.maps.Projection} [projection] May be set to use a different projection than that returned by this.getProjection().
 * @param {Element}                [div]        May be set to specify a different map viewport than this.getDiv() (only used to get dimensions).
 * @return {google.maps.LatLngBounds} the calculated bounds.
 *
 * @example
 * var bounds = map.boundsAt(5); // same as map.boundsAt(5, map.getCenter(), map.getProjection(), map.getDiv());
 */
google.maps.Map.prototype.boundsAt = function (zoom, center, projection, div) {
    var p = projection || this.getProjection();
    if (!p) return undefined;
    var d = $(div || this.getDiv());
    var zf = Math.pow(2, zoom) * 2;
    var dw = d.getStyle('width').toInt()  / zf;
    var dh = d.getStyle('height').toInt() / zf;
    var cpx = p.fromLatLngToPoint(center || this.getCenter());
    return new google.maps.LatLngBounds(
        p.fromPointToLatLng(new google.maps.Point(cpx.x - dw, cpx.y + dh)),
        p.fromPointToLatLng(new google.maps.Point(cpx.x + dw, cpx.y - dh)));
}

抱歉让大家久等了 - 我忘记了这个问题 :) - giorgiga
请展示如何将其制作成一个完整的工作示例,例如从https://developers.google.com/maps/documentation/javascript/examples/groundoverlay-simple开始。 - Dan Jacobson
你好,您之前发布了很久以前的帖子,但我很好奇。p代表投影,d代表除法,dw代表宽度的除法,dh代表高度的除法,cpx代表中心像素,但zf代表什么意思呢? - Cedric Arnould
“缩放因子” - 可能不是最好的选择 :) - giorgiga
这就是为什么语义很重要的原因 :) - Stuart

0

你在这里的使用情况是什么?

你可以在v2 API中计算这个:

map.getBoundsZoomLevel(bounds);

然而在v3 API中没有办法做到这一点。


谢谢,broady - 我知道v3 API没有内置的方法来做那个 :) 使用案例可能有点复杂,但最终我只需要将{center, zoom}转换为一个LatLngBounds对象... 无论如何,我现在已经完成了一半:当我有时间回到那个Google地图项目时,我会发布任何成功的消息。 - giorgiga

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接