javascript - 从中心和缩放计算边界(Google Maps API v3)

标签 javascript google-maps google-maps-api-3

我需要计算给定中心和缩放级别的 map 边界。

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

有人知道如何在 v3 中执行此操作吗?

最佳答案

这使用了一些 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)));
}

关于javascript - 从中心和缩放计算边界(Google Maps API v3),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3774579/

相关文章:

javascript - 用 typescript 迭代 map 不起作用

google-maps - 如何获取谷歌地图位置名称?

javascript - 谷歌地图自动完成 Material 设计

javascript - Google Maps API v3 返回灰色 block

javascript - 在 jQuery 中应用 css 方法后,css 类/属性处于非事件状态

Javascript 与 Jquery : Initializing Modals. 函数在 JS 中无法识别,但在 jQuery 中

jquery - 在谷歌地图中创建自定义信息窗口

javascript - 异步执行作为参数传递的函数

javascript - 在 Chartkick.js 中添加价格标签

javascript - 如何检测为 GroundOverlay 加载的进度