使用 google_maps_flutter 插件抖动折线距离

问题描述

您好,我正在使用 google_maps_Flutter 插件,并在我的地图上显示了一条折线。我想做的是计算折线长度的距离。我的代码linked here,下面有一个片段。我不想使用 Directions API。如何计算折线距离并打印到控制台?感谢阅读。

"street"

解决方法

假设您要计算由 latlngSegment1 中的点创建的折线的距离。

为此,您需要计算 latlngSegment1 中每个连续 LatLng 点之间的距离。

我会用这样的东西来做。

            double calculateDistane(List<LatLng> polyline) {
                double totalDistance = 0;
                for (int i = 0; i < polyline.length; i++) {
                  if (i < polyline.length - 1) { // skip the last index
                    totalDistance += getStraightLineDistance(
                        polyline[i + 1].latitude,polyline[i + 1].longitude,polyline[i].latitude,polyline[i].longitude);
                  }
                }
               return totalDistance;
              }

              double getStraightLineDistance(lat1,lon1,lat2,lon2) {
                var R = 6371; // Radius of the earth in km
                var dLat = deg2rad(lat2 - lat1);
                var dLon = deg2rad(lon2 - lon1);
                var a = math.sin(dLat / 2) * math.sin(dLat / 2) +
                    math.cos(deg2rad(lat1)) *
                        math.cos(deg2rad(lat2)) *
                        math.sin(dLon / 2) *
                        math.sin(dLon / 2);
                var c = 2 * math.atan2(math.sqrt(a),math.sqrt(1 - a));
                var d = R * c; // Distance in km
                return d * 1000; //in m
              }

              dynamic deg2rad(deg) {
                return deg * (math.pi / 180);
              }

注意:getStraightLineDistance() 函数给出了两个纬度点之间的直线距离,这可能不是某人从 A 点到达 B 点的方式。