google maps – Calculating the distance between two latitude and longitude points in android-ThrowExceptions

Exception or error:

How can i find the distance between `two``latitude` & `longitude` points

For one of the latitude & longitude points i have it in database & another one i want to use current position of the mobile

Which one should i need to use them among below::

• android location provider
• Mathematical Calculation

note:: Any demo code sample will be useful

How to solve:

You can use the built in algorithm:

``````Location locationA = new Location("point A");
locationA.setLatitude(latA);
locationA.setLongitude(lngA);
Location locationB = new Location("point B");
locationB.setLatitude(latB);
LocationB.setLongitude(lngB);
distance = locationA.distanceTo(locationB) ;
``````

update: (I don’t have any error with this)

``````LatLng latLngA = new LatLng(12.3456789,98.7654321);
LatLng latLngB = new LatLng(98.7654321,12.3456789);

Location locationA = new Location("point A");
locationA.setLatitude(latLngA.latitude);
locationA.setLongitude(latLngA.longitude);
Location locationB = new Location("point B");
locationB.setLatitude(latLngB.latitude);
locationB.setLongitude(latLngB.longitude);

double distance = locationA.distanceTo(locationB);
``````

###

You can use the Haversine algorithm. Another user has already coded a solution for this:

``````public double CalculationByDistance(double initialLat, double initialLong,
double finalLat, double finalLong){
int R = 6371; // km