Android: How do I set the zoom level of map view to 1 km radius around my current location?

binW picture binW · May 14, 2011 · Viewed 51.7k times · Source

I want to set the map view zoomed to 1km radius but cant figure out how?

The doc says that the zoom level 1 will map earths equator to 256 pixels. So how do I calculate which zoom level I need to set so that the map view shows area in 1KM radius?

UPDATE:
After reading a few blog posts I wrote the following code:

private int calculateZoomLevel() {
    double equatorLength = 6378140; // in meters
    double widthInPixels = screenWidth;
    double metersPerPixel = equatorLength / 256;
    int zoomLevel = 1;
    while ((metersPerPixel * widthInPixels) > 2000) {
        metersPerPixel /= 2;
        ++zoomLevel;
    }
    Log.i("ADNAN", "zoom level = "+zoomLevel);
    return zoomLevel;
}

The idea is that first I calculate Meters per pixel in the zoom level 1, which according to google shows equator of earth using 256 pixels. Now every subsequent zoom level magnifies by a level of 2 so I half the meters per pixel for every zoom level. I do this until I have a zoom level where meters per pixel multiplied by the screen width gives me less than 2000 i.e 2 Km across.

But I dont think that the zoom level I am getting is showing the map of 2Km radius. Can some one tell me what I am doing wrong here?

Answer

Syed Raza Mehdi picture Syed Raza Mehdi · Apr 14, 2014

although this answer is logical and i find it working but the results are not accurate i dont know why but i tired this approach and this technique is far more accurate.

1) Make a circle on object with desired radius

Circle circle = mGoogleMap.addCircle(new CircleOptions().center(new LatLng(latitude, longitude)).radius(getRadiusInMeters()).strokeColor(Color.RED));           
        circle.setVisible(true);
        getZoomLevel(circle);

2) Pass that object to this function and set the zoom level Here's a link

public int getZoomLevel(Circle circle) {
if (circle != null){
    double radius = circle.getRadius();
    double scale = radius / 500;
    zoomLevel =(int) (16 - Math.log(scale) / Math.log(2));
}
return zoomLevel;
}