How to convert a LatLng and a radius to a LatLngBounds in Android Google Maps API v2?

Warlax picture Warlax · Mar 10, 2013 · Viewed 28.8k times · Source

I believe this is a limitation of the recent Google Maps API v2. They have recently added the ability to draw a Circle on the ground - but if you want to position the camera such that it shows the entire Circle, there exists no way to do so.

One can call CameraUpdateFactory#newLatLngBounds(bounds, padding) where "bounds" is a LatLngBounds and "padding" is a distance in pixels. The issue is that there is no way to create a LatLng and a radius into a LatLngBounds.

The constructor for LatLngBounds only takes 2 LatLng instances and generates a rectangle where these are the NW and SE corners.

Answer

Bartek Lipinski picture Bartek Lipinski · Jun 24, 2015

Just like Risadinha mentioned, you can easily achieve that with android-maps-utils. Just add:

compile 'com.google.maps.android:android-maps-utils:0.4.4'

to your gradle dependencies, use the following code:

public LatLngBounds toBounds(LatLng center, double radiusInMeters) {
    double distanceFromCenterToCorner = radiusInMeters * Math.sqrt(2.0);
    LatLng southwestCorner =
                SphericalUtil.computeOffset(center, distanceFromCenterToCorner, 225.0);
    LatLng northeastCorner = 
                SphericalUtil.computeOffset(center, distanceFromCenterToCorner, 45.0);
    return new LatLngBounds(southwestCorner, northeastCorner);
}

EDIT:

Our goal is to calculate two points (LatLngs):

  • southwestCorner

and

  • northeastCorner

From the javadoc of the SphericalUtil you can read that 225 and 45 are heading values, and the distanceFromCenterToCorner is the distance. Further explanation of the values in the picture below:

visual explanation