I've been tasked to set a feature which requires setting the default view on google maps to be 50 miles radius around the user's location. Here's my implementation
private fun calculateZoomLevel(): Float {
val equatorLength = 40075017.0
val displayMetrics = DisplayMetrics()
@Suppress("DEPRECATION")
val widthInPixels = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R){
requireActivity().windowManager.defaultDisplay.getMetrics(displayMetrics)
displayMetrics.widthPixels
} else {
val windowMetrics = requireActivity().windowManager.currentWindowMetrics
val insets = windowMetrics.windowInsets.getInsetsIgnoringVisibility(WindowInsets.Type.systemBars())
windowMetrics.bounds.width().minus(insets.left).minus(insets.right)
}
val equatorLengthInPx = dpToPx(256) // I've tried 256 in px or dp.. In both cases, the default view is still far from the 50 miles radius view
Log.e(this::class.java.simpleName, "Length in pixel: $equatorLengthInPx")
var metersPerPixel = equatorLength / equatorLengthInPx
var zoomLevel = 1
val radiusInMeters = milesToMeters(50.0)
while ((metersPerPixel * widthInPixels) > radiusInMeters) {
metersPerPixel /= 2
zoomLevel++
}
Log.e(this::class.java.simpleName, "zoom level = $zoomLevel")
return zoomLevel.toFloat()
}
I tested this but the map is viewed on a radius < 10 miles
I tried a couple of solutions from this link: Android: How do I set the zoom level of map view to 1 km radius around my current location?
None of them provide a more reliable calculation. Any ideas are welcomed