fetchW3WGrid method

Future<void> fetchW3WGrid({
  1. required LatLng center,
  2. double delta = 0.001,
})

Fetch and update W3W grid for the given bounding box.

Implementation

Future<void> fetchW3WGrid({
  required LatLng center,
  double delta = 0.001,
}) async {
  final boundingBox = W3WGridConverter.calculateBoundingBox(center, delta);

  if (!W3WGridConverter.isValidBoundingBox(
    swLat: boundingBox.swLat,
    swLng: boundingBox.swLng,
    neLat: boundingBox.neLat,
    neLng: boundingBox.neLng,
  )) {
    return;
  }

  final cacheKey = '${boundingBox.swLat},${boundingBox.swLng},${boundingBox.neLat},${boundingBox.neLng}';
  final currentTime = DateTime.now();

  if (_gridCache.containsKey(cacheKey) &&
      currentTime.difference(_gridCacheTimestamps[cacheKey]!).compareTo(GRID_CACHE_DURATION) < 0) {
    gridPolylines = _gridCache[cacheKey]!;
    notifyListeners();
    return;
  }

  isGridLoading = true;
  notifyListeners();

  try {
    final gridData = await getGridSection(
      swLat: boundingBox.swLat,
      swLng: boundingBox.swLng,
      neLat: boundingBox.neLat,
      neLng: boundingBox.neLng,
    );

    gridPolylines = W3WGridConverter.convertGridToPolylines(
      gridData,
      gridColor: Colors.blue,
      opacity: 0.4,
    );

    _gridCache[cacheKey] = gridPolylines;
    _gridCacheTimestamps[cacheKey] = currentTime;

    errorMessage = null;
  } catch (e) {
    debugPrint('Error fetching grid: $e');
    gridPolylines = {};
  } finally {
    isGridLoading = false;
    notifyListeners();
  }
}