Total distance calculation from LatLng List

前端 未结 5 724
梦毁少年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 03:09

    I've used the vector_math for converting degree to radians and also the geolocator for getting the current user latitude and longitude if in case searching from the current location also there is a method where in you can calculate the distance between two locations directly as Geolocator.distanceBetween(startLatitude, startLongitude, endLatitude, endLongitude).

    import 'dart:math' show sin, cos, sqrt, atan2;
    import 'package:vector_math/vector_math.dart';
    import 'package:geolocator/geolocator.dart';
    
    Position _currentPosition;
    double earthRadius = 6371000; 
    
    //Using pLat and pLng as dummy location
    double pLat = 22.8965265;   double pLng = 76.2545445; 
    
    
    //Use Geolocator to find the current location(latitude & longitude)
    getUserLocation() async {
       _currentPosition = await GeoLocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
    }
    
    //Calculating the distance between two points without Geolocator plugin
    getDistance(){
       var dLat = radians(pLat - _currentPosition.latitude);
       var dLng = radians(pLng - _currentPosition.longitude);
       var a = sin(dLat/2) * sin(dLat/2) + cos(radians(_currentPosition.latitude)) 
               * cos(radians(pLat)) * sin(dLng/2) * sin(dLng/2);
       var c = 2 * atan2(sqrt(a), sqrt(1-a));
       var d = earthRadius * c;
       print(d); //d is the distance in meters
    }
    
    //Calculating the distance between two points with Geolocator plugin
    getDistance(){
       final double distance = Geolocator.distanceBetween(pLat, pLng, 
               _currentPosition.latitude, _currentPosition.longitude); 
       print(distance);
    }
    

提交回复
热议问题