Total distance calculation from LatLng List

前端 未结 5 728
梦毁少年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:56

    Try this please. I tested it with Google Maps and works accurately. You can do a loop and find total distance by using 2 points each time. I added some random dummy data to show how it works. Copy this code to https://dartpad.dartlang.org/ and test easily.

    import 'dart:math' show cos, sqrt, asin;
    
    void main() {
      double calculateDistance(lat1, lon1, lat2, lon2){
        var p = 0.017453292519943295;
        var c = cos;
        var a = 0.5 - c((lat2 - lat1) * p)/2 + 
              c(lat1 * p) * c(lat2 * p) * 
              (1 - c((lon2 - lon1) * p))/2;
        return 12742 * asin(sqrt(a));
      }
    
      List data = [
        {
          "lat": 44.968046,
          "lng": -94.420307
        },{
          "lat": 44.33328,
          "lng": -89.132008
        },{
          "lat": 33.755787,
          "lng": -116.359998
        },{
          "lat": 33.844843,
          "lng": -116.54911
        },{
          "lat": 44.92057,
          "lng": -93.44786
        },{
          "lat": 44.240309,
          "lng": -91.493619
        },{
          "lat": 44.968041,
          "lng": -94.419696
        },{
          "lat": 44.333304,
          "lng": -89.132027
        },{
          "lat": 33.755783,
          "lng": -116.360066
        },{
          "lat": 33.844847,
          "lng": -116.549069
        },
      ];
      double totalDistance = 0;
      for(var i = 0; i < data.length-1; i++){
        totalDistance += calculateDistance(data[i]["lat"], data[i]["lng"], data[i+1]["lat"], data[i+1]["lng"]);
      }
      print(totalDistance);
    }
    

提交回复
热议问题