如何在Android App中检测Nearst可用的纬度和经度

时间:2017-09-26 04:31:35

标签: android geolocation

我有关于他们的经度和纬度的同事的数据。我想检测最近的用户位置关联。用户位置我会用Android SDK检测到。 我的问题如何以这样的方式匹配params,APP可以显示最好的最近的同事。在此先感谢。

2 个答案:

答案 0 :(得分:0)

考虑你的同伴列表是lats longs的非null数组。

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
}

答案 1 :(得分:0)

我假设你有一个POJO Associates,其中LongitudesLatitudes分别为associate,{ s说你有一个Array的同事然后找到最近的用户位置,使用这个简短的逻辑:

 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;
        }
    }