createGeofence method

Future<Map<String, dynamic>> createGeofence({
  1. required String name,
  2. required List<List<double>> coordinates,
  3. required String webhookUrl,
})

Implementation

Future<Map<String, dynamic>> createGeofence({
  required String name,
  required List<List<double>> coordinates,
  required String webhookUrl,
}) async {
  if (coordinates.length < 3) {
    throw GeoEngineException(
        "Se requieren al menos 3 puntos para un polĂ­gono");
  }

  final polygon = coordinates.map((p) => [p[1], p[0]]).toList();

  if (polygon.first[0] != polygon.last[0] ||
      polygon.first[1] != polygon.last[1]) {
    polygon.add(polygon.first);
  }

  final payload = {
    "name": name,
    "webhook_url": webhookUrl,
    "geojson": {
      "type": "Polygon",
      "coordinates": [polygon]
    }
  };

  final uri = Uri.parse('$managementUrl/geofences');

  if (debug) print('[GeoEngine] Creating geofence: $name');

  try {
    final response = await _client
        .post(
          uri,
          headers: _headers,
          body: jsonEncode(payload),
        )
        .timeout(timeout);

    if (response.statusCode >= 400) {
      throw GeoEngineException('Management Error: ${response.body}',
          statusCode: response.statusCode);
    }

    return jsonDecode(response.body);
  } on TimeoutException {
    throw GeoEngineException('Connection timed out');
  } catch (e) {
    if (debug) print('[GeoEngine] Error: $e');
    rethrow;
  }
}