Droid_Interceptor
Droid_Interceptor

Reputation: 663

Calculating distance between two locations. Value only changes if Longitude is changed

I am using this code to calculate the the distance between two points. I am using the Haversine formula

private double CalcDistance(Location Start, Location End) 
    {
        // TODO Auto-generated method stub
        double distance;
        double lat1 = Start.getLatitude();
        double lat2 = End.getLatitude();
        double lng1 = Start.getLongitude();
        double lng2 = End.getLongitude();
        double dLat = Math.abs(Math.toRadians(lat2-lat1));
        double dLng = Math.abs(Math.toRadians(lng2 - lng1));

        distance = Math.sin(dLat/2) * Math.sin(dLng/2) + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) * 
                Math.sin(dLng/2) * Math.sin(dLng/2);

        double c = 2 * Math.asin(Math.sqrt(distance));

        //Return the answer in Kilometre (6371km the mean radius of the earth)
        return c * 6371;
    }

The valus that is produced only changes if the Longitude of the Location is changed and stays the same if the Latitude is changed. Is there any reason my code only does this.

Upvotes: 0

Views: 729

Answers (2)

FabianCook
FabianCook

Reputation: 20587

Hey I'm not entirely sure, but just looking at your code you might have made an error, I dont understand it but perhaps you could change

distance = Math.sin(dLat/2) * Math.sin(dLng/2) + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) * 
                Math.sin(dLng/2) * Math.sin(dLng/2);

to

distance = 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);

Upvotes: 1

Dmitry Shkuropatsky
Dmitry Shkuropatsky

Reputation: 3965

You need to change

Math.sin(dLat/2) * Math.sin(dLng/2)

to

Math.sin(dLat/2) * Math.sin(dLat/2)

Upvotes: 1

Related Questions