Sandip Armal Patil
Sandip Armal Patil

Reputation: 5895

How to calculate difference between longitude latitude?

I need to calculate the difference between longitude and latitude of current position
and previous position. but it display the result in Exponential format and I need it in
metres. I don't understand how to convert it in metre format. Which formula require for that?

double distance2 = distanceCalculate(lat,lng,locationB.getLatitude(),locationB.getLongitude());
Toast.makeText(this, "distance2=="+Double.valueOf(distance2).longValue() + "meter" , Toast.LENGTH_SHORT).show(); 

double ActualDistance=(Double.valueOf(distance2).longValue())/1E6;
if(ActualDistance<400)
{
    System.out.println("identical");
    Toast.makeText(this,"identical", Toast.LENGTH_LONG).show();
}
else
{
    // send sms
    SmsManager sms = SmsManager.getDefault();
}

public static float distanceCalculate (double lat1, double lng1, double lat2, double 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();
}

Upvotes: 3

Views: 2732

Answers (3)

Julien
Julien

Reputation: 3529

On this question, I found this code :

public static double distFrom(double lat1, double lng1, double lat2, double 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; 

  return dist; 
} 

It's a java implementation of Haversine formula.

It will return the distance in miles. For other units change the earthRadius with http://en.wikipedia.org/wiki/Earth_radius

Upvotes: 1

Pben
Pben

Reputation: 1101

i find this in JavaScript i think it's can help you to understand how you can do it

Upvotes: 2

Rowland Shaw
Rowland Shaw

Reputation: 38129

That's a simple one -- currently you're using the radius of the Earth in miles; simply change that for the radius in metres (per Wikipedia: 6,371,000), and remove your conversion

Upvotes: 1

Related Questions