Question

Calculate the distance between 2 points based on their GeoPoint coordinates. find distance your location and where you want to go location .

 private double mesafe() {
// TODO Auto-generated method stub

 // 6378.1 is gravity of earth
 double EARTH_RADIUS = 6371;


double latitude = 38.452261 ;
double longitude = 27.216243 ;

Location locationA = new Location("EGE");

         /*your location*/
Location lc = new Location("KONUM");

currentLat = lc.getLatitude();//your location Latitude
currentLon = lc.getLongitude(); //your location Longitude

double lat2 = currentLat;
double lon2 = currentLon;

//The difference between latitudes and longitudes
double deltalat = Math.toRadians( lat2 - latitude) ;
double deltalon = Math.toRadians(lon2 - longitude) ;
double a=Math.sin(deltalat / 2)*Math.sin(deltalat/2)+
  Math.cos(Math.toRadians(latitude))* Math.sin(deltalon / 2) 
                             * Math.sin(deltalon / 2);

double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 

double distance = EARTH_RADIUS*c; //find your distance

mesafee.setText(String.valueOf(distance)+"  km"); 

return distance;
  } 

This code find distance but incorrect.

Was it helpful?

Solution

I wrote this code using the Haversine formular for distance calculation:

private Double calculateDistance(double lat1, final double lon1, double lat2, final double lon2) {
    final int R = 6371; // earth radius in km
    final double dLat = Math.toRadians(lat2-lat1);
    final double dLon = Math.toRadians(lon2-lon1);
    lat1 = Math.toRadians(lat1);
    lat2 = Math.toRadians(lat2);

    double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
               Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));

    return R * c;
  }

Keep in mind, this is a straight-line (airline) distance of course, not a route. If you need a road-distance it's a whole different story, and you'll need some kind of routing-server. You could e.g. use Google Maps APIs, have a look at the Distance Matrix API or the Directions API.

OTHER TIPS

Use this method,

Location locationA = new Location("point A");

locationA.setLatitude(orginlat); locationA.setLongitude(orginlong);

Location locationB = new Location("point B");

locationB.setLatitude(tolat); locationB.setLongitude(tolong);

Float distance = locationA.distanceTo(locationB);

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top