Last active
March 15, 2016 04:37
-
-
Save mickey35vn/49c586e9eac7f7a23bc2 to your computer and use it in GitHub Desktop.
Calculate the zoom level of bounds
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
private let LN2 = 0.6931471805599453 | |
private let WORLD_PX_HEIGHT = 256 | |
private let WORLD_PX_WIDTH = 256 | |
func getBoundsZoomLevel(bounds: GMSCoordinateBounds, mapWidthPx: Int, mapHeightPx: Int) -> Double { | |
let ne = bounds.northEast | |
let sw = bounds.southWest | |
let latFraction = (getLatitudeRadius(ne.latitude) - getLatitudeRadius(sw.latitude)) / M_PI | |
let lngDiff = ne.longitude - sw.longitude | |
let lngFraction = ((lngDiff < 0) ? (lngDiff + 360) : lngDiff) / 360 | |
let latZoom = getZoomWithFraction(mapHeightPx, worldPx: WORLD_PX_HEIGHT, fraction: latFraction) | |
let lngZoom = getZoomWithFraction(mapWidthPx, worldPx: WORLD_PX_WIDTH, fraction: lngFraction) | |
return min(latZoom, lngZoom) | |
} | |
func getLatitudeRadius(lat: Double) -> Double { | |
let sinLat = sin(lat * M_PI / 180) | |
let radX2 = log((1 + sinLat) / (1 - sinLat)) / 2 | |
return max(min(radX2, M_PI), -M_PI) / 2 | |
} | |
func getZoomWithFraction(mapPx: Int, worldPx: Int, fraction: Double) -> Double { | |
return floor(log(Double(mapPx) / Double(worldPx) / fraction) / LN2) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment