如何计算两点之间的道路距离?

时间:2018-06-19 07:00:09

标签: android google-maps

在我的Android应用程序中,我计划为产品添加运费(每公里X美元),那么,我如何计算两点之间的公路距离?

我们的产品将从固定位置发送,但用户将提供目的地位置。

有人可以为此提供详细的方法吗?

3 个答案:

答案 0 :(得分:2)

您可以使用google map API。 你会得到这样的回应:

{
  "destination_addresses" : [ "New York, NY, USA" ],
  "origin_addresses" : [ "Washington, DC, USA" ],
  "rows" : [
    {
      "elements" : [
        {
          "distance" : {
            "text" : "225 mi",
            "value" : 361715
          },
          "duration" : {
            "text" : "3 hours 49 mins",
            "value" : 13725
          },
          "status" : "OK"
        }
      ]
    }
  ],
  "status" : "OK"
}

如果需要,您还可以使用纬度和经度。

答案 1 :(得分:0)

使用此代码,它将接受起点lat lng和目标点lat lng和retunrn距离KM

 public static double calculateDistanceBetweenTwoPoints(double startLat, double startLong, double endLat, double endLong) {
    double earthRadiusKm = 6372.8; //Earth's Radius In kilometers
    double dLat = Math.toRadians(endLat - startLat);
    double dLon = Math.toRadians(endLong - startLong);
    startLat = Math.toRadians(startLat);
    endLat = Math.toRadians(endLat);
    double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(startLat) * Math.cos(endLat);
    double c = 2 * Math.asin(Math.sqrt(a));
    double haverdistanceKM = earthRadiusKm * c;
    return haverdistanceKM;
}

答案 2 :(得分:0)

如果您使用Google Maps API并使用polyLines,只需调用 .getDistanceValue()即可获得距离。下面的代码将向您展示如何在textview中显示距离值,计算地图中的2个点。

 private List<Polyline> polylines;
private static final int[] COLORS = new int[]{R.color.primary_dark_material_light};
@Override
public void onRoutingSuccess(ArrayList<Route> route, int shortestRouteIndex) {
    if(polylines.size()>0) {
        for (Polyline poly : polylines) {
            poly.remove();
        }
    }

    polylines = new ArrayList<>();
    for (int i = 0; i <route.size(); i++) {

        int colorIndex = i % COLORS.length;

        PolylineOptions polyOptions = new PolylineOptions();
        polyOptions.color(getResources().getColor(COLORS[colorIndex]));
        polyOptions.width(10 + i * 3);
        polyOptions.addAll(route.get(i).getPoints());
        Polyline polyline = mMap.addPolyline(polyOptions);
        polylines.add(polyline);

        TextView friendDist = (TextView) findViewById(R.id.distance);

        //following line will generate the distance
        friendDist.setText("Distance: "+ route.get(i).getDistanceValue() +" meters");

    }

}
相关问题