Created
August 25, 2014 22:55
-
-
Save pix0r/95c5fa839105a6c01cb1 to your computer and use it in GitHub Desktop.
Ruby implementation of getBoundsZoomLevel JS
This file contains hidden or 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
def zoom_level_for_bounds(bounds, map_dim={ height: 1000, width: 1000 }, zoom_max=21) | |
# See: http://stackoverflow.com/a/13274361/72 | |
return zoom_max if bounds.min_x == bounds.max_x and bounds.min_y == bounds.max_y | |
world_dim = { height: 256, width: 256 } | |
def lat_rad(lat) | |
sin = Math.sin(lat * Math::PI / 180) | |
rad_x2 = Math.log((1 + sin) / (1 - sin)) / 2 | |
[[rad_x2, Math::PI].min, -Math::PI].max / 2 | |
end | |
def zoom(map_px, world_px, fraction) | |
(Math.log(map_px / world_px / fraction) / Math.log(2)).floor | |
end | |
lat_fraction = (lat_rad(bounds.max_x) - lat_rad(bounds.min_x)).abs / Math::PI | |
lng_diff = bounds.max_y - bounds.min_y | |
lng_fraction = ((lng_diff < 0) ? (lng_diff + 360) : lng_diff) / 360 | |
lat_zoom = zoom(map_dim[:height], world_dim[:height], lat_fraction) | |
lng_zoom = zoom(map_dim[:width], world_dim[:width], lng_fraction) | |
return [lat_zoom, lng_zoom, zoom_max].min | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment