Comparing two locations using their Longitude and Latitude

风流意气都作罢 提交于 2019-11-27 11:58:45

You actually need to implement a function called distance that will calculate the distance between two locations. Calculating the distance between two locations is one possible way of comparing the longitude and latitude values.

An example of comparing them:

@Override
public void onLocationChanged(Location location) {

 double lat2 = location.getLatitude();
 double lng2 = location.getLongitude();

    // lat1 and lng1 are the values of a previously stored location
    if (distance(lat1, lng1, lat2, lng2) < 0.1) { // if distance < 0.1 miles we take locations as equal
       //do what you want to do...
    }
}

/** calculates the distance between two locations in MILES */
private double distance(double lat1, double lng1, double lat2, double lng2) {

    double earthRadius = 3958.75; // in miles, change to 6371 for kilometer output

    double dLat = Math.toRadians(lat2-lat1);
    double dLng = Math.toRadians(lng2-lng1);

    double sindLat = Math.sin(dLat / 2);
    double sindLng = Math.sin(dLng / 2);

    double a = Math.pow(sindLat, 2) + Math.pow(sindLng, 2)
        * Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2));

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

    double dist = earthRadius * c;

    return dist; // output distance, in MILES
}

You can use the Location class's static distanceBetween() method like so:

    float[] distance = new float[1];
    Location.distanceBetween(lat, lon, currentLat, currentLon, distance);
    // distance[0] is now the distance between these lat/lons in meters
    if (distance[0] < 2.0) {
        // your code...
    }

If you have two Location objects, another option is distanceTo()

All the 4 input parameters are in float. Distance is a relative one not real distance. You need to convert this distance to a real distance by searching some formula online :( I used this in my app to get nearest metro station from my current location. Hope this snippet helps someone :)

float distance(float lat,float lon,float clat,float clon)
{
    float distance;
    float temp1;
    float temp2;
    temp1=(float)((lat-clat)*(lat-clat));
    temp2=(float)((lon-clon)*(lon-clon));
    distance=temp1+temp2;
    return distance;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!