代码之家  ›  专栏  ›  技术社区  ›  giorgiga

计算中心和缩放的边界(Google地图API v3)

  •  3
  • giorgiga  · 技术社区  · 14 年前

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

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

    有人知道在v3中怎么做吗?

    2 回复  |  直到 14 年前
        1
  •  9
  •   giorgiga    14 年前

    这需要一些moootools,因此您必须编辑代码,以便与其他库一起使用(应该足够简单)。

    /**
     * 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)));
    }
    
        2
  •  0
  •   Chris Broadfoot    14 年前

    你这里的用例是什么?

    您可以在V2 API中计算:

    map.getBoundsZoomLevel(bounds);

    但是,在v3 api中无法做到这一点。