找出谷歌地图中两个位置的距离

时间:2016-04-13 10:09:56

标签: android google-maps

我使用以下距离公式来找出距离b / w andorid中的两个位置,但没有给出准确的距离

public double calculatedistancenew(String s1,String s2)  {

 int Radius=6371;//radius of earth in Km         
 double dLat = Math.toRadians(lati-Double.valueOf(s1));
 double dLon = Math.toRadians(longg-Double.valueOf(s2));
 double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
 Math.cos(Math.toRadians(lati)) * Math.cos(Math.toRadians(Double.valueOf(s1))) * Math.sin(dLon/2) * Math.sin(dLon/2);
 double c = 2 * Math.asin(Math.sqrt(a));
 double valueResult= Radius*c;
 double km=valueResult/1;
 DecimalFormat newFormat = new DecimalFormat("####");
 float kmInDec =  Float.valueOf(newFormat.format(km));
 double meter=valueResult%1000;
 int  meterInDec= Integer.valueOf(newFormat.format(meter));
 Log.i("Radius Value",""+valueResult+"   KM  "+kmInDec+" Meter   "+meterInDec);
 double kmindis=Math.floor(valueResult*100)/100;
 return kmindis;

}

2 个答案:

答案 0 :(得分:0)

使用以下代码计算两个位置之间的距离

Location location1 = new Location("A");
Location location2 = new Location("B");

location1.setLatitude(dLat1);
location1.setLongitude(dLon1);

location2.setLatitude(dLat2);
location2.setLongitude(dLon2);

float distance = location1.distanceTo(location2);`

计算出的值以米为单位。

答案 1 :(得分:0)

这很容易做到,你可以查看googlemaps utils库,方法" computeDistanceBetween":

https://github.com/googlemaps/android-maps-utils/blob/9085396a1cb5703db568241937ffa330ff099d4e/library/src/com/google/maps/android/SphericalUtil.java

static double havDistance(double lat1, double lat2, double dLng) {
    return hav(lat1 - lat2) + hav(dLng) * cos(lat1) * cos(lat2);
}

static double arcHav(double x) {
    return 2 * asin(sqrt(x));
}

private static double distanceRadians(double lat1, double lng1, double lat2, double lng2) {
    return arcHav(havDistance(lat1, lat2, lng1 - lng2));
}

static double computeAngleBetween(LatLng from, LatLng to) {
    return distanceRadians(toRadians(from.latitude), toRadians(from.longitude),
                           toRadians(to.latitude), toRadians(to.longitude));
}

public static double computeDistanceBetween(LatLng from, LatLng to) {
    return computeAngleBetween(from, to) * EARTH_RADIUS;
}

有些方法可能会丢失refences,请查看github代码以获取完整代码!

相关问题