1

I have data of associates with their Longitudes and Latitudes. I want to detect the nearest associate to the User Location. user location i will detect with the Android SDK. My Question how to match the params in such a way that APP can show the best nearest associates. thanks in Advance.

2 Answers2

0

Considering your list of associates is non-null array of lats longs.

LatLng GetNearest(LatLng myPos, LatLng[] Associates)
{
    double nearestDistance = distance(myPos.lat, myPos.lng, Associates[0].lat,Associates[0].lng);
    LatLng Nearest = Associates[0];
    for(int i = 1; i < Associates.length(); i ++)
    {
       double _d =  distance(myPos.lat, myPos.lng, Associates[i].lat, Associates[i].lng);
       if(_d < nearestDistance)
      {
           nearestDistance = _d;
           Nearest  = Associates[i];

      }
    }
  return Nearest;
}

/** 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
}
0

I assume you have a POJO of Associates, in which you have Longitudes and Latitudes for each of your associate, So let's say you have an Array of associates then to find the nearest to user location, use this short and simple logic :

 for (Associates associate : associates) {
        Double associateLatitude = associate.getLatitude();
        Double associateLongitude = associate.getLongitude();

        android.location.Location locationOne = new android.location.Location("");
        locationOne.setLatitude(userLatitude);
        locationOne.setLongitude(userLongitude);

        android.location.Location locationTwo = new android.location.Location("");
        locationTwo.setLongitude(associateLongitude);
        locationTwo.setLatitude(associateLatitude);

        float distance = locationOne.distanceTo(locationTwo);
        if (disTemp == 0.0f) {
            disTemp = distance;
            nearestAssociate = associate;
        } else if (disTemp > distance) {
            disTemp = distance;
            nearestAssociate = associate;
        }
    }
Anurag
  • 1,162
  • 6
  • 20