android – Retrieve distance from visible part of Google map-ThrowExceptions

Exception or error:

I want to draw a static circle over a map with Google Maps. When the user pinches, the map will zoom in/out.

I need to know the map radius (related to the area contained in the circle) and change the seekbar at the bottom accordingly.

Does anybody know a solution how to retrieve the distance from the left to the right screen edge? I didn’t find anything at the Google Maps API doc.

Something like this:

enter image description here

How to solve:

using VisibleRegion you can get the all corner cordinates and also the center.

VisibleRegion vr = mMap.getProjection().getVisibleRegion();
double left = vr.latLngBounds.southwest.longitude;
double top = vr.latLngBounds.northeast.latitude;
double right = vr.latLngBounds.northeast.longitude;
double bottom = vr.latLngBounds.southwest.latitude;

and you can calcuate distance from two region by this

Location MiddleLeftCornerLocation;//(center's latitude,vr.latLngBounds.southwest.longitude)
Location center=new Location("center");
center.setLatitude( vr.latLngBounds.getCenter().latitude);
center.setLongitude( vr.latLngBounds.getCenter().longitude);
float dis = center.distanceTo(MiddleLeftCornerLocation);//calculate distane between middleLeftcorner and center 

enter image description here

###

I got a while to write the code for “MiddleLeftCornerLocation” variable in the great answer given by @Md. Monsur Hossain Tonmoy, so just to complete it (I haven’t enough reputation points to comment your answer, sorry):

    VisibleRegion vr = map.getProjection().getVisibleRegion();
    double bottom = vr.latLngBounds.southwest.latitude;

    Location center = new Location("center");
    center.setLatitude(vr.latLngBounds.getCenter().latitude);
    center.setLongitude(vr.latLngBounds.getCenter().longitude);

    Location middleLeftCornerLocation = new Location("center");
    middleLeftCornerLocation.setLatitude(center.getLatitude());
    middleLeftCornerLocation.setLongitude(left);

    float dis = center.distanceTo(middleLeftCornerLocation);

###

First get the map center point with

googleMap.getCameraPosition().target;

then figure out the width of the map and get the height/2 and convert them to a Point using the x y values you just got.

then relate that point to the map

LatLng widthPoint = map.getProjection().fromScreenLocation(point);

now that you have the tagret point and the width point you can calculate the distance between the 2 points which will give you the radius.

Note

this assumes always in portrait mode, if you are in landscape mode the circle will be bigger than the visible area so in this case you will want to get the distance from the height

Leave a Reply

Your email address will not be published. Required fields are marked *