Create a function to sort documents by proximity to the user's location.

Hi,

I have no coding knowledge whatsoever, but I am trying generate a functionality where a pageview reorders itself with the click of a 'Nearby' button. I am trying to build a function that takes in the user's current location, a list of documents with location and sort it according to the nearest document first.

I tried custom code and got errors.

errors:
The getter 'latLng' isn't defined for the type 'VideoPostsRecord'.
Try importing the library that defines 'latLng', correcting the name to the name of an existing getter, or defining a getter or field named 'latLng'

here is the code:

import 'dart:convert';
import 'dart:math' as math;

import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:intl/intl.dart';
import 'package:timeago/timeago.dart' as timeago;
import '/flutter_flow/lat_lng.dart';
import '/flutter_flow/place.dart';
import '/flutter_flow/uploaded_file.dart';
import '/flutter_flow/custom_functions.dart';
import '/backend/backend.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import '/auth/firebase_auth/auth_util.dart';

List<VideoPostsRecord> sortByProximity(
  List<VideoPostsRecord> videoPost,
  LatLng userLocation,
) {
  /// MODIFY CODE ONLY BELOW THIS LINE

  // Create a function to sort documents by proximity to the user's location using haversine method.
// Haversine formula to calculate distance between two points on earth
  double _distance(LatLng latLng1, LatLng latLng2) {
    const double earthRadius = 6371.0; // in km
    final double lat1 = math.pi / 180.0 * latLng1.latitude;
    final double lat2 = math.pi / 180.0 * latLng2.latitude;
    final double lon1 = math.pi / 180.0 * latLng1.longitude;
    final double lon2 = math.pi / 180.0 * latLng2.longitude;
    final double dLat = lat2 - lat1;
    final double dLon = lon2 - lon1;
    final double a = math.pow(math.sin(dLat / 2), 2) +
        math.cos(lat1) * math.cos(lat2) * math.pow(math.sin(dLon / 2), 2);
    final double c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a));
    final double distance = earthRadius * c;
    return distance;
  }

  // Sort the video posts by proximity to the user's location
  videoPost.sort((a, b) {
    final double distanceA = _distance(
      LatLng(a.latLng.latitude, a.latLng.longitude),
      userLocation,
    );
    final double distanceB = _distance(
      LatLng(b.latLng.latitude, b.latLng.longitude),
      userLocation,
    );
    return distanceA.compareTo(distanceB);
  });

  return videoPost;

  /// MODIFY CODE ONLY ABOVE THIS LINE
}
2
6 replies