Home > Software design >  How to get the average LatLng Coordinates from a List of LatLng in Flutter / Dart
How to get the average LatLng Coordinates from a List of LatLng in Flutter / Dart

Time:08-01

I have the following List of LatLng Coordinates. I want to make a function with calculates and returns the Average LatLng Coordinate from all of the LatLngs from the List except the last one (because the Last one is always the same like the first one).

final listOfLatLngs = [
    const LatLng(50.08155798581401, 8.24199914932251),
    const LatLng(50.08053216096673, 8.242063522338867),
    const LatLng(50.080614778545716, 8.243619203567505),
    const LatLng(50.0816956787534, 8.243404626846313),
    const LatLng(50.08155798581401, 8.24199914932251),
  ];

My formular looks like this but it isnt complete and really functional:

getAverage() {
    double averageLatitude = 0;
    double averageLongitude = 0;

    ///Removes the last LatLng Coordinate
    listOfLatLngs.removeLast();
    print("Length of List: ${listOfLatLngs.length}");

    averageLatitude = (listOfLatLngs[0].latitude  
            listOfLatLngs[1].latitude  
            listOfLatLngs[2].latitude  
            listOfLatLngs[3].latitude) /
        4;

    averageLongitude = (listOfLatLngs[0].longitude  
            listOfLatLngs[1].longitude  
            listOfLatLngs[2].longitude  
            listOfLatLngs[3].longitude) /
        4;

    print("Average Latitude: $averageLatitude");
    print(
        "Average Latitude: $averageLatitude, Average Longitude: $averageLongitude");
  }

Only Problem is that this function won't work if the List is longer then an index of 4.

The Average LatLng Coordinate should be:

LatLng(50.08110015101990, 8.24277162551880)

enter image description here

List of LatLng is the Polygon (Rectangle on the Map), Marker is the Average LatLng.

Does anyone know how to do this?

Grateful for every Comment!

CodePudding user response:

You can achieve this with a normal for loop and get the average like this

void main() {
final listOfLatLngs = [
    LatLng(50.08155798581401, 8.24199914932251),
    LatLng(50.08053216096673, 8.242063522338867),
    LatLng(50.080614778545716, 8.243619203567505),
    LatLng(50.0816956787534, 8.243404626846313),
    LatLng(50.08155798581401, 8.24199914932251),
  ];
  
  double totalLat = 0.0;
  double totalLng = 0.0;
  for(int i = 0; i < (listOfLatLngs.length-1); i  )
  {
    totalLat  = listOfLatLngs[i].latitude;
    totalLng  = listOfLatLngs[i].longitude;
  }
  print("Average Latitude : ${totalLat/(listOfLatLngs.length-1)} and Average Longitude : ${totalLng/(listOfLatLngs.length-1)}");
 
}

//OUTPUT
//Average Latitude : 50.08110015101996 and Average Longitude : 8.242771625518799
  • Related