Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
540 views
in Technique[技术] by (71.8m points)

javascript - Calculate bounds from center and zoom (Google Maps API v3)

I need to calculate the bounds of a map given center and zoom level.

I imagine I could temporarily set map center and zoom and call map.getBounds(), but I would prefer not to (I would need to disable/re-enable a few event handlers).

Does anybody know how to do this in v3?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This uses a bit of mootools, so you'll have to edit the code to use it with other libraries (should be easy enough).

/**
 * 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)));
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...