我正在尝试确定一种方法来识别一组位置中的哪个位置最接近用户。我首先尝试确定2个位置之间的距离。到目前为止,我编写代码的方式只允许我确定一次该距离-即用户仅靠近一个位置。我正在使用自定义位置提供程序来获取经纬度。我的代码如下。为了解决这个问题,我们做了很多研究,但是我发现的解决方案已经过时,或者对于应该是一个简单任务的解决方案来说似乎太复杂了。任何帮助将不胜感激。
@Override
public void gotCurrentLocation (Location location) {
Location locCL = new Location("");
locCL.setLatitude(location.getLatitude());
locCL.setLongitude(location.getLongitude());
Location locIFC = new Location("");
locIFC.setLatitude(xxxx);
locIFC.setLongitude(xxxx);
Location locBGC = new Location ("" );
locBGC.setLatitude(xxxx);
locBGC.setLongitude(xxxx);
float distanceInMeters = locCL.distanceTo(locIFC);
float distanceInMeters = locCL.distanceTo(locBGC);
}
答案 0 :(得分:2)
/**
* @param startLat gps lat
* @param startLong gps lon
* @param endLat exti lat
* @param endLong exit long
* @return distance in KM
* @since 02040215
* <p>Distance, bearing and more between Latitude/Longitude points</p>
* <p> R is earth’s radius (mean radius = 6,371km)</p>
* <p/>
* <p>var lat1Red = lat1.toRadians();</p>
* <p>var lat2Red = lat2.toRadians();</p>
* <p>var delLat = (lat2 - lat1).toRadians();</p>
* <p>var delLong = (lon2 - lon1).toRadians();</p>
* <p>var a = Math.sin(delLat / 2) * Math.sin(delLat / 2) +</p>
* <p> Math.cos(delLat) * Math.cos(lat2Red) *</p>
* <p> Math.sin(delLong / 2) * Math.sin(delLong / 2);</p>
* <p> var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));</p>
* <p> var d = R * c;</p>
* <p/>
* *
*/
public double calculateDistanceBetween2Point(double startLat, double startLong, double endLat, double endLong) {
/** * R is earths radius (mean radius = 6,371km) */
double earthR = 6371e3;
double dagToRad = Math.PI / 180;
double radStartLat;
double radStartLong;
double radEndLat;
double radEndLong;
double distance = 0;
double dalLat;
double dalLong;
radStartLat = startLat * dagToRad;
radStartLong = startLong * dagToRad;
radEndLat = endLat * dagToRad;
radEndLong = endLong * dagToRad;
dalLat = radEndLat - radStartLat;
dalLong = radEndLong - radStartLong;
double a = Math.sin(dalLat / 2) * Math.sin(dalLat / 2) + Math.cos(radStartLat) *
Math.cos(radEndLat) * Math.sin(dalLong / 2) * Math.sin(dalLong / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
distance = earthR * c;
return distance;
}
我认为这会对您有所帮助。
答案 1 :(得分:0)
我在我的项目中使用了它
private double distanceOfDestination(double _fromLatitude,double _toLatitude,double _fromLatitude,double _toLongitude) {
double distance = 0.0;
double earthRadius = 3958.75;
double latDiff = Math.toRadians(_toLatitude - _fromLatitude);
double lngDiff = Math.toRadians(_toLongitude - _fromLongitude);
double a = Math.sin(latDiff / 2) * Math.sin(latDiff / 2) +
Math.cos(Math.toRadians(_fromLatitude)) * Math.cos(Math.toRadians(_toLongitude)) *
Math.sin(lngDiff / 2) * Math.sin(lngDiff / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
distance = earthRadius * c;
int meterConversion = 1609;
return new Float(distance * meterConversion).floatValue();
}