Total distance calculation from LatLng List

前端 未结 5 712
梦毁少年i
梦毁少年i 2020-12-16 02:19

Im using dart/flutter and the \'package:latlong/latlong.dart\' to parse a GPX file into a list of LatLng objects. That is working fine, but the next step is to

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-16 02:55

    This function calculates the distance between two points (given the latitude/longitude of those points).

    unit = the unit you desire for results              
          where: 'M' is statute miles (default) 
                 'K' is kilometers            
                 'N' is nautical miles
    String distance(
              double lat1, double lon1, double lat2, double lon2, String unit) {
             double theta = lon1 - lon2;
             double dist = sin(deg2rad(lat1)) * sin(deg2rad(lat2)) +
             cos(deg2rad(lat1)) * cos(deg2rad(lat2)) * cos(deg2rad(theta));
             dist = acos(dist);
             dist = rad2deg(dist);
             dist = dist * 60 * 1.1515;
              if (unit == 'K') {
                dist = dist * 1.609344;
              } else if (unit == 'N') {
                dist = dist * 0.8684;
              }
              return dist.toStringAsFixed(2);
            }
    
        double deg2rad(double deg) {
          return (deg * pi / 180.0);
        }
    
        double rad2deg(double rad) {
          return (rad * 180.0 / pi);
        }
    
        void main() {
          print("Distance : " + distance(32.9697, -96.80322, 29.46786, -98.53506, 'K'));
        }
    

提交回复
热议问题