【问题标题】:Calculate bounds from center and zoom (Google Maps API v3)从中心和缩放计算边界(Google Maps API v3)
【发布时间】:2011-04-16 00:46:01
【问题描述】:

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

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

有人知道如何在 v3 中做到这一点吗?

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • 抱歉耽搁了伙计们-我忘记了这个问题:)
    • 请展示如何制作一个完整的工作示例,例如,以developers.google.com/maps/documentation/javascript/examples/…开头
    • 嗨,你很久以前发布过,但我很好奇,p = 投影,d = div,dw = div,宽度,dh = div 高度,cpx = 中心像素但这是什么意思zf?
    • "缩放系数" - 可能不是最佳选择 :)
    【解决方案2】:

    你的用例是什么?

    您可以在 v2 API 中计算:

    map.getBoundsZoomLevel(bounds);

    但是在 v3 API 中没有办法做到这一点。

    【讨论】:

    • 谢谢,broady - 我知道 v3 API 没有内置的方法可以做到这一点:) 用例解释起来有点复杂,但最后我只需要转换 {center , zoom} 到一个 LatLngBounds 对象......无论如何我现在已经完成了一半:我会发布我获得的任何成功(当我有时间回到那个谷歌地图项目时)
    猜你喜欢
    • 1970-01-01
    • 2015-04-14
    • 2011-08-28
    • 2023-04-03
    • 1970-01-01
    • 2016-07-20
    • 1970-01-01
    • 1970-01-01
    • 2021-11-24
    相关资源
    最近更新 更多