Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate distance between two locations using their longitude and latitude value

Tags:

android

Here my code I used below code to calculate the distance between two location using their latitude and longitude. It is giving wrong distance. sometimes getting right and sometimes getting irrelevant distance.

We are getting lat1 and lng1 from database.

//getting lat2 and lng2 from GPS as below  public class MyLocationListener implements LocationListener {    @Override   public void onLocationChanged(Location loc)   {     lat2=loc.getLatitude();     lng2=loc.getLongitude();     String Text = "My current location is: " +"Latitud = "+ loc.getLatitude() +"Longitud = " + loc.getLongitude();      //System.out.println("Lat & Lang form Loc"+Text);     //Toast.makeText( getApplicationContext(), Text,Toast.LENGTH_SHORT).show();   }    @Override   public void onProviderDisabled(String provider)   {   }    @Override   public void onProviderEnabled(String provider)   {   }    @Override   public void onStatusChanged(String provider, int status, Bundle extras)   {   }     //Calculating distance   double earthRadius = 3958.75;    double dLat = Math.toRadians(lat1-lat2);   double dLng = Math.toRadians(lng1-lng2);   double a = Math.sin(dLat/2) * Math.sin(dLat/2) +              Math.cos(Math.toRadians(lat2)) * Math.cos(Math.toRadians(lat1)) *              Math.sin(dLng/2) * Math.sin(dLng/2);   double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));   double dist = earthRadius * c; 
like image 211
raghumudem Avatar asked Aug 08 '11 12:08

raghumudem


2 Answers

Here getting distance in miles (mi)

private double distance(double lat1, double lon1, double lat2, double lon2) {     double theta = lon1 - lon2;     double dist = Math.sin(deg2rad(lat1))                      * Math.sin(deg2rad(lat2))                     + Math.cos(deg2rad(lat1))                     * Math.cos(deg2rad(lat2))                     * Math.cos(deg2rad(theta));     dist = Math.acos(dist);     dist = rad2deg(dist);     dist = dist * 60 * 1.1515;     return (dist); }  private double deg2rad(double deg) {     return (deg * Math.PI / 180.0); }  private double rad2deg(double rad) {     return (rad * 180.0 / Math.PI); } 
like image 38
Rasel Avatar answered Oct 07 '22 16:10

Rasel


There is an android.location.Location.distanceBetween() method which does this quite well.

Android Developer Docs: Location

like image 153
Nikolay Elenkov Avatar answered Oct 07 '22 16:10

Nikolay Elenkov