1

Possible Duplicate:
Distance between geopoints

I have some latitudes and longitudes and i need to find the nearest locations with these latitude and longitudes from my current place

Community
  • 1
  • 1
Vamshi
  • 1,495
  • 1
  • 15
  • 31

1 Answers1

1

try this,

public class getDistanceList 
{
/**
 * 
 * @param lat1 Latitude of the First Location
 * @param lng1 Logitude of the First Location
 * @param lat2 Latitude of the Second Location
 * @param lng2 Longitude of the Second Location
 * @return distance between two lat-lon in float format
 */

public static float distFrom (float lat1, float lng1, float lat2, float lng2 ) 
{
    double earthRadius = 3958.75;
    double dLat = Math.toRadians(lat2-lat1);
    double dLng = Math.toRadians(lng2-lng1);
    double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
    Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
    Math.sin(dLng/2) * Math.sin(dLng/2);
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    double dist = earthRadius * c;

    int meterConversion = 1609;

    return new Float(dist * meterConversion).floatValue();
}
David M
  • 71,481
  • 13
  • 158
  • 186
Lucifer
  • 29,392
  • 25
  • 90
  • 143
  • if i have 30 lat and 30 longitudes then how to find which is the nearest – Vamshi Jan 19 '12 at 12:46
  • well then you need to run a for loop for 30 times here your first lat-long will be same and next lat-long will be your 30 different lal-long, now find the distance & get the answer you want – Lucifer Jan 19 '12 at 12:49
  • no i want the distance from current location with these lat-long, not with the 1st lat-long – Vamshi Jan 19 '12 at 12:52
  • dear, thats what I am telling , your first lat-long will be your current location's lat-long & last 2 arguments will be the 30 different values that you have . now first time it will calculate values for current location & first lat-lon, then next time current location & 2nd lat-long. got it ? – Lucifer Jan 19 '12 at 12:55
  • Yes i got it thanks, but how to find current locations lat-long – Vamshi Jan 19 '12 at 12:57
  • Will below code works?? LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); double longitude = location.getLongitude(); double latitude = location.getLatitude(); – Vamshi Jan 19 '12 at 12:59
  • yes, It will surely works. I am using same for my current application – Lucifer Jan 19 '12 at 13:00
  • I will check and accept your answer but it is helpful for me – Vamshi Jan 19 '12 at 13:06