Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 743
Salman Khan Avatar asked Jan 18 '13 07:01

Salman Khan


People also ask

Can Google Maps API calculate distance between two points?

The API returns information based on the recommended route between start and end points. You can request distance data for different travel modes, request distance data in different units such kilometers or miles, and estimate travel time in traffic.


2 Answers

In Google Map API V2 You have LatLng objects so you can't use distanceTo (yet).

You can then use the following code considering oldPosition and newPosition are LatLng objects :

// The computed distance is stored in results[0]. //If results has length 2 or greater, the initial bearing is stored in results[1]. //If results has length 3 or greater, the final bearing is stored in results[2]. float[] results = new float[1]; Location.distanceBetween(oldPosition.latitude, oldPosition.longitude,                 newPosition.latitude, newPosition.longitude, results); 

For more informations about the Location class see this link

like image 195
Fr4nz Avatar answered Oct 12 '22 07:10

Fr4nz


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;     } 
like image 22
Usman Kurd Avatar answered Oct 12 '22 08:10

Usman Kurd