Search code examples
androidgoogle-maps-api-2

Find distance between two points on map using Google Map API V2


I am using google map api v2 in my android application, I am able to show the map and put markers on it, but now I am stuck with the problem in which I need to find out the distance between two markers or points placed on map, I have already gone through the docs but didn't find anything helpful in this case.

If anyone knows how to solve this then please help me.

Thanks


Solution

  • You can use the following method that will give you accurate result

    public double CalculationByDistance(LatLng StartP, LatLng EndP) {
            int Radius = 6371;// radius of earth in Km
            double lat1 = StartP.latitude;
            double lat2 = EndP.latitude;
            double lon1 = StartP.longitude;
            double lon2 = EndP.longitude;
            double dLat = Math.toRadians(lat2 - lat1);
            double dLon = Math.toRadians(lon2 - lon1);
            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.asin(Math.sqrt(a));
            double valueResult = Radius * c;
            double km = valueResult / 1;
            DecimalFormat newFormat = new DecimalFormat("####");
            int kmInDec = Integer.valueOf(newFormat.format(km));
            double meter = valueResult % 1000;
            int meterInDec = Integer.valueOf(newFormat.format(meter));
            Log.i("Radius Value", "" + valueResult + "   KM  " + kmInDec
                    + " Meter   " + meterInDec);
    
            return Radius * c;
        }