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.
Asked
Active
Viewed 48 times
1
-
try https://stackoverflow.com/questions/18170131/comparing-two-locations-using-their-longitude-and-latitude – Ganesh Gudghe Sep 26 '17 at 04:33
2 Answers
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