Wednesday, June 22, 2011

Android : Calculate distance between two GeoPoints on MapView.

Code to calculate distance between two GeoPoints on MapView:


private static final double Radius = 6371;

int width = mapView.getWidth();
int height = mapView.getHeight();

GeoPoint northEastCorner = projection.fromPixels(myPoint.x-(width/2), myPoint.y-(height/2));

double lat1 = centerGeoPoint.getLatitudeE6()/1E6;
double lat2 = northEastCorner.getLatitudeE6()/1E6;

double lon1 = centerGeoPoint.getLongitudeE6()/1E6;
double lon2 = northEastCorner.getLongitudeE6()/1E6;

double dLat = Math.toRadians(lat2-lat1);
double dLon = Math.toRadians(lon2-lon1);

double a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
Math.sin(dLon/2) * Math.sin(dLon/2);

double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));

double r = Radius * c;

3 comments: