Skip to content

Instantly share code, notes, and snippets.

@kibotu
Last active April 3, 2025 06:27
Show Gist options
  • Save kibotu/e09e48b143d4816062818a6820d03b78 to your computer and use it in GitHub Desktop.
Save kibotu/e09e48b143d4816062818a6820d03b78 to your computer and use it in GitHub Desktop.
Google Maps Calculate Zoom
/**
* 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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment