Android distance between two points

android, dictionary

Solution

http://developer.android.com/reference/android/location/Location.html

Use the distanceTo or distanceBetween methods. Why dont you try the Android's Location method here

You can create a Location object from a latitude and longitude:

Location location = new Location("");
location.setLatitude(lat);
location.setLongitude(lon);

Problem

I have 3 ways to calculate the distance and all 3 gives me different answers, ``` double lat = 6.924049; double lng = 79.853807; double lat1 = 6.856461; double lng1 = 79.912748; ``` How to calculate the distance between two points and how to percent it on Km? or Meters? 1st way ans = 9.967441199417708E-6 ``` float[] results = new float[1]; Location.distanceBetween(lat / 1E6, lng / 1E6, lat1 / 1E6, lng1 / 1E6,results); float s =results[0] * 0.000621371192f; String a2 = Float.toString(s); ``` 2nd way ans = 6.1795527E6 ``` double lat3 = lat / 1E6; double lat2 = lat1 / 1E6; double lon3 = lng / 1E6; double lon2 = lng1 / 1E6; double dLat = Math.toRadians(lat2 - lat3); double dLon = Math.toRadians(lon2 - lon3); double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) * Math.sin(dLon / 2) * Math.sin(dLon / 2); double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); // 6378.1 is gravity of earth double asd = c * 6378.1; ``` 3rd way ans =6.176576174444191 ``` { double a5 = distance(lat, lng, lat1, lng1); String a6 = Double.toString(a5); } 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); } ``` So, How to calculate the distance between two points and how to percent it on KM ? or Meters ?

Original source

Related problems