如何从KML文件中获取路径长度?

时间:2012-05-21 09:29:32

标签: android google-maps kml

我有包含路线信息的KML文件。现在我需要知道这条路线的长度以千米为单位。我看到标签中的KML文件中有这个长度,如下所示:

<description><![CDATA[Distance: 750&#160;m (about 2 mins)<br/>Map data ©2012 Google]]></description>

但在我看来,解析这个字符串是错误的。 将不胜感激任何替代和/或建议! 谢谢!

1 个答案:

答案 0 :(得分:2)

我认为最好的解决方案是使用路线点的坐标来计算路线长度。这是解决这个问题的代码:

ArrayList<GeoPoint> points;
private static final int EARTH_RADIUS = 6371;

.....
            for(int i = 0; i < (points.size() - 1); ++i) {
               final double lat1 = toRadians(points.get(i).getLatitudeE6() / LocationHelper.MILLION);
               final double lat2 = toRadians(points.get(i + 1).getLatitudeE6() / LocationHelper.MILLION);
               final double lon1 = toRadians(points.get(i).getLongitudeE6() / LocationHelper.MILLION);
               final double lon2 = toRadians(points.get(i + 1).getLongitudeE6() / LocationHelper.MILLION);

               length += acos(sin(lat1)*sin(lat2) + cos(lat1)*cos(lat2) * cos(lon2 - lon1)) * EARTH_RADIUS;
            }
        road.length = round(length, 2, BigDecimal.ROUND_HALF_UP);

....
private static double round(double unrounded, int precision, int roundingMode)
{
    final BigDecimal bd = new BigDecimal(unrounded);
    final BigDecimal rounded = bd.setScale(precision, roundingMode);
    return rounded.doubleValue();
}