Created
September 4, 2014 22:12
-
-
Save pieterv/163010b20a6664e722a3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Get zoom level to fit in | |
* | |
* @see http://stackoverflow.com/questions/6048975/google-maps-v3-how-to-calculate-the-zoom-level-for-a-given-bounds | |
* | |
* @param bounds | |
* @param mapWidth | |
* @param mapHeight | |
* @returns {number} | |
*/ | |
function zoomLevelToFitBounds(bounds, mapWidth, mapHeight) { | |
var worldWidth = 256; | |
var worldHeight = 256; | |
var ZOOM_MAX = 21; | |
function latRad(lat) { | |
var sin = Math.sin(lat * Math.PI / 180); | |
var radX2 = Math.log((1 + sin) / (1 - sin)) / 2; | |
return Math.max(Math.min(radX2, Math.PI), -Math.PI) / 2; | |
} | |
function zoom(mapPx, worldPx, fraction) { | |
return Math.floor(Math.log(mapPx / worldPx / fraction) / Math.LN2); | |
} | |
var ne = bounds.getNorthEast(); | |
var sw = bounds.getSouthWest(); | |
var latFraction = (latRad(ne.lat()) - latRad(sw.lat())) / Math.PI; | |
var lngDiff = ne.lng() - sw.lng(); | |
var lngFraction = ((lngDiff < 0) ? (lngDiff + 360) : lngDiff) / 360; | |
var latZoom = zoom(mapHeight, worldHeight, latFraction); | |
var lngZoom = zoom(mapWidth, worldWidth, lngFraction); | |
return Math.min(latZoom, lngZoom, ZOOM_MAX); | |
} | |
module.exports = zoomLevelToFitBounds; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment