Google Maps Calculate Zoom
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
/** | |
* Calculates the zoom level for the StreetWatchMap using the formula given by a Google employee (maps team) | |
* in https://groups.google.com/d/msg/google-maps-js-api-v3/hDRO4oHVSeM/osOYQYXg2oUJ. For simplification | |
* the formula has been duplicated and simplified below | |
* | |
* R = RequestedMeterRadius | |
* S = MinScreenSizeInDp | |
* B = BaseMetersPerPixel (for the type of map) | |
* L = Latitude (Center of focus) | |
* Z = ZoomLevel | |
* | |
* (2R)/S = (B * Cos(L * PI / 180)) / (2^Z) | |
* | |
* which solving for Z becomes | |
* Z = log2((B * Cos(L * PI / 180) * S) / (2R)) | |
* | |
* @param viewSize The size of the [MapView] in DP | |
* @param geoLocation The location at the center of the view | |
* @param requestedRadius The radius around the [geoLocation] in Meters | |
*/ | |
fun calculateZoom(viewSize: Point, geoLocation: GeoLocation, requestedRadius: Int): Float { | |
val latitudeRadian = geoLocation.latitude * Math.PI / 180 | |
val top = BASE_METER_PER_DP * Math.cos(latitudeRadian) * Math.min(viewSize.x, viewSize.y) | |
val total = top / (requestedRadius * 2).toFloat() | |
return total.log(2.0).toFloat() | |
} | |
val zoomLevel = calculateZoom(Point(mapView.width.pxToDp(), mapView.height.pxToDp()), geoLocation, radius) | |
val cameraUpdate = CameraUpdateFactory.newCameraPosition( | |
CameraPosition.Builder().apply { | |
target(LatLng(geoLocation.latitude, geoLocation.longitude)) | |
zoom(zoomLevel) | |
}.build() | |
) | |
map.moveCamera(cameraUpdate); |