Vitor Pereira
Vitor Pereira

Reputation: 11

Distance between points

I'm trying to create a function so that I return the distance between various points on the map, based on where I am and the rest of the points.

But so can get the distance obtained at the first point of the database.

Could you help me?

if (cursor.getCount() > 0) {
    if (cursor != null && cursor.moveToFirst()) {       
        lat_s = >cursor.getString(cursor.getColumnIndex("latitude"));
        lng_s = >cursor.getString(cursor.getColumnIndex("longitude"));          
        lat_p = Double.parseDouble(lat_s);
        lng_p = Double.parseDouble(lng_s);          
        double dist = getDistancia(lat, lng, lat_p, lng_p);         
    }       
    @SuppressWarnings("deprecation")        
    SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this,
        R.layout.list_row, cursor, from, to);       
    listView.setAdapter(mAdapter);  
}

and the function to return me the distance is:

public double getDistancia(double latitude, double longitude, 
        double latitudePto, double longitudePto){  
    double dlon, dlat, a, distancia;  
    dlon = longitudePto - longitude;  
    dlat = latitudePto - latitude;  
    a = Math.pow(Math.sin(dlat/2),2) + Math.cos(latitude) * 
            Math.cos(latitudePto) * Math.pow(Math.sin(dlon/2),2);  
    distancia = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));  
    return 6378140 * distancia; /* 6378140 is the radius of the Earth in meters*/  
}

Upvotes: 0

Views: 564

Answers (3)

yuva ツ
yuva ツ

Reputation: 3703

Google map has provided api for getting distance between two Locations-

For more details

https://developers.google.com/maps/documentation/directions/

You can also use this-

Location locationA = new Location("point A");  
locationA.setLatitude(mLatitude / 1E6);  
locationA.setLongitude(mLongitude / 1E6);  
Location locationB = new Location("point B");  
locationB.setLatitude(lat / 1E6);  
locationB.setLongitude(lng / 1E6);  
double distance = locationA.distanceTo(locationB);

Upvotes: 1

Joan P.S
Joan P.S

Reputation: 1573

Check out this code, there are a few utils that could help you with this :)

https://github.com/BeyondAR/beyondar/blob/master/android/BeyondAR_Framework/src/com/beyondar/android/util/math/Distance.java

Upvotes: 0

An-droid
An-droid

Reputation: 6485

Don't understand the question but here is an element of solution :

protected double distanceBetween(float lat_a, float lng_a, float lat_b, float lng_b) {

    float pk = (float) (180 / 3.14169);
    float a1 = lat_a / pk;
    float a2 = lng_a / pk;
    float b1 = lat_b / pk;
    float b2 = lng_b / pk;
    float t1 = FloatMath.cos(a1) * FloatMath.cos(a2) * FloatMath.cos(b1) * FloatMath.cos(b2);
    float t2 = FloatMath.cos(a1) * FloatMath.sin(a2) * FloatMath.cos(b1) * FloatMath.sin(b2);
    float t3 = FloatMath.sin(a1) * FloatMath.sin(b1);
    double tt = Math.acos(t1 + t2 + t3);
    return 6366000 * tt;
}

Upvotes: 0

Related Questions